python - Google Colab 中的 OpenCV Python 用于多个图像:max Contour 函数不起作用
问题描述
我目前正在使用 Google Colab 编写用于面部图像的脚本。我正在使用 Haar 正面面部检测,为其拟合一个矩形,使用该区域内的最大轮廓将椭圆拟合到面部。当我尝试将函数 max() 用于轮廓“cnts”时,我收到错误“ValueError: max() arg is an empty sequence”。打印时的 Cnts 具有值,并且列表已填充。max() 函数适用于单个图像。关于如何让它再次运行的任何建议?TIA
from collections import Iterable
import math
def flatten(lis):
for item in lis:
if isinstance(item, Iterable) and not isinstance(item, str):
for x in flatten(item):
yield x
else:
yield item
detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
for i in range (0, len(X_data)):
gray = cv2.cvtColor(X_data[i], cv2.COLOR_RGB2GRAY)
rects = detector.detectMultiScale(gray, scaleFactor=1.05, #rects returns the values of the bounding boxes
minNeighbors=5, minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE)
# loop over the bounding boxes
for (x, y, w, h) in rects:
crop_img = gray[y-5:(y+h+5) , x-5:(x+w+5)] #crop each image with a border of 10 pixels for each with the bounding box
th, threshed = cv2.threshold(crop_img, 100, 255, cv2.THRESH_BINARY) #thresholding image to aid finding contours within the cropped image, possible improvement needed
cnts, hiers = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE, offset=(x,y)) #find contours in the thresheld image
print(cnts)
c = max(cnts, key = cv2.contourArea) #find maximum contour in the image
cnt_list=list(flatten(c))
print (cnt_list) #flatten the largest contour
ellipse=cv2.fitEllipse(c)
cv2.ellipse(X_data[i], ellipse, (23, 184, 80), 3)
#print ('ellipse: ',ellipse)
print(ellipse[0][0])
centre_x=ellipse[0][0]
centre_y=ellipse[0][1]
minor_b=ellipse[1][0]
major_a=ellipse[1][1]
angle=ellipse[2]
解决方案
推荐阅读
- css - 为图像提供圆形背景而不进行裁剪
- sql - 如果按序列分组不同,则聚合值不同
- javascript - Eslint“半”规则不检查类方法的结尾
- android - requestLocationUpdates(例如 10 000 毫秒)不影响 GnssMeasurementEvent.CallBack onGnssMeasurementsReceived() 更新间隔
- java - 有没有办法在 Java 中使用泛型参数自己的泛型参数?
- php - openssl_x509_fingerprint():无法从参数 1 获取证书
- php - crypt 函数 PHP 以普通形式显示盐
- promise - https.post.promise “.then” 未调用
- android-room - 根据房间数据库中的时间戳值检索数据
- javascript - 如何从 Angular 的侧边栏菜单进行切换?