如何标记OpenCV中两个数组中存在的特性?

2024-04-23 20:49:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个python3.7脚本,使用opencvhaar分类器文件检测人脸和特征,该文件将图像存储为n维Numpy数组。现在我只使用两个功能: -整张脸 -眼睛 这两种方法都是使用两种不同的分类器得到的。 代码检测图像中是否存在这两个特征,然后在for循环中使用cv2.rectangle()函数为每个特征标记一个矩形,即一个用于检测到的人脸,一个用于检测到的眼睛。你知道吗

我希望脚本标记的眼睛矩形只有当这些点是在脸阵列以及眼睛阵列中找到。numpy.1D交叉点()只在一维数组中找到交集。你知道吗

我甚至试过

for x,y,w,h in eyes and x,y,w,h in faces:

它只会返回以下错误消息:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

任何帮助都将不胜感激。你知道吗

这是在Windows1064位上尝试的,代码是用PyCharm2019编写的,OpenCV作为CV2导入。你知道吗

# Creating the cascade classifier objects.
face_cascade = 
cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
eye_cascade = cv2.CascadeClassifier("haarcascade_eye.xml")

# Entering and displaying the original image.
img = cv2.imread("filename.jpg", 1)
cv2.imshow("Original Images",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Convert the image to Black and White and store in a variable.
gry_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gry_img, scaleFactor = 1.05, minNeighbors = 8)
eyes = eye_cascade.detectMultiScale(gry_img, scaleFactor = 1.30, minNeighbors = 12)

# Now, we mark the detected features with a rectangle on the original image.
for x,y,w,h in faces:
    img = cv2.rectangle(img, (x,y), (x+w, y+h), (255, 21, 21), 3) # Blue.


for x,y,w,h in eyes:
    img = cv2.rectangle(img, (x,y), (x+w, y+h), (255, 255, 24), 3) # Cyan.

cv2.imshow("Detected Faces and Eyes",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

我需要的眼睛特征,只有当他们也被发现在面部特征阵列标记。你知道吗


Tags: andthein标记imageimgfor特征
2条回答

哦,天哪,我现在是不是觉得自己傻了。好吧,这里是:

正如ZdaR所说,OpenCV文档确实提供了一个关于如何实现我所要求的结果的完美示例,其要点是:

for x,y,w,h in faces:
    face_img = gry_img[y:y+h, x:x+w]
    # Now detect the eyes in this `face_img` only.
    eyes = eye_cascade.detectMultiScale(face_img, scaleFactor = 1.30, minNeighbors = 12)

除此之外,我需要做的显然是将原始图像裁剪到面部坐标,以便绘制眼睛特征。我仍然不确定这个是否应该起作用,但目前看来,添加额外的行确实起作用。你知道吗

最终有效的代码:

faces = face_cascade.detectMultiScale(gry_img, scaleFactor = 1.05, minNeighbors = 10)
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y),(x + w, y + h), (255, 0, 0), 3)
    gry_eye = gry_img[y:y+h, x:x+w]
    eye_img = img[y:y + h, x:x + w]
    eyes = eye_cascade.detectMultiScale(gry_eye, scaleFactor = 1.05, minNeighbors = 5)
    for (x, y, w, h) in eyes:
        cv2.rectangle(eye_img, (x, y), (x + w, y + h), (255, 255, 24), 3)

嗯,这是一次学习的经历。 感谢ZdaR的帮助!你知道吗

解决这个问题的更好方法已经在OpenCV docs中提出。它建议您不要通过整个图像来检测眼睛,而应该首先检测人脸,然后裁剪图像,并使用此裁剪图像来检测眼睛。要裁剪面部图像,可以使用numpy切片:

for x,y,w,h in faces:
    face_img = gry_img[y:y+h, x:x+w]
    # Now detect the eyes in this `face_img` only.
    eyes = eye_cascade.detectMultiScale(face_img, scaleFactor = 1.30, minNeighbors = 12)

相关问题 更多 >