发生错误的原因是您传递的Unicode对象要作为图像文件读取。该行作为Unicode img = easygui.fileopenbox()返回img,而不是按预期返回的图像数组。
你怎么转换这个?首先将unicode转换为字符串。unicodedata为此目的,有一个图书馆。(我已经在下面的代码中展示了如何使用它)
接下来读取此字符串并将生成的图像文件存储为数组。
以下代码将帮助您解决问题
码:import numpy as np
import cv2
import easygui
import unicodedata
path = 'C:/Users/Jackson/Desktop/Stack/face_detection/'
face_cascade = cv2.CascadeClassifier(path + 'haarcascade_frontalface_default.xml')
uni_img = easygui.fileopenbox()
img_path = unicodedata.normalize('NFKD', uni_img).encode('ascii','ignore')
img = cv2.imread(img_path, 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
更新:
我已对您提供的代码进行了必要的修改。只需复制以下内容并执行它:import numpy as np
import cv2 as cv
import easygui
face_cascade = cv.CascadeClassifier('face.xml')
def todo():
#--- returns the Unicode ---
uni_code = easygui.fileopenbox()
#--- converting unicode to string ---
img_path = unicodedata.normalize('NFKD', uni_code).encode('ascii','ignore')
img = cv2.imread(img_path, 1)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 7, 7)
for (x,y,w,h) in faces:
cv.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()
todo()