I'm trying to code a face recognition app using OpenCV and python on macOS 'Big Sur' and Pycharm, but unfortunately it does not show the image window/preview and it does not show any errors in console , below you can check code:
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('news.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face = face_cascade.detectMultiScale(gray_img,
scaleFactor=1.05, minNeighbors=5)
for x, y, w, h in face:
img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 3)
resized = cv2.resize(img, (int(img.shape[1]/3), int(img.shape[0]/3)))
# cv2.startWindowThread()
# cv2.namedWindow("preview")
cv2.imshow('preview', img)
cv2.waitKey(0)
cv2.destroyWindow('preview')
I have tried adding cv2.startWindowThread(), cv2.namedWindow("preview") and even installed headless by "pip3 install opencv-python-headless" but it does not work.
Replace the line face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
with face_cascade = cv2.CascadeClassifier(cv2.data.haarcascade + 'haarcascade_frontalface_default.xml')
and then it should work fine
Here's the final code :
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascade + 'haarcascade_frontalface_default.xml')
img = cv2.imread('news.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face = face_cascade.detectMultiScale(gray_img,
scaleFactor=1.05, minNeighbors=5)
for x, y, w, h in face:
img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 3)
resized = cv2.resize(img, (int(img.shape[1]/3), int(img.shape[0]/3)))
# cv2.startWindowThread()
# cv2.namedWindow("preview")
cv2.imshow('preview', img)
cv2.waitKey(0)
cv2.destroyWindow('preview')