在Pycharm中新建python腳本,輸入如下代碼
import cv2 filename = '/home/utryjc/Pictures/timg.jpeg' def detect(filename): face_cascade = cv2.CascadeClassifier('/home/utryjc/opencv-3.2.0/data/haarcascades_cuda/haarcascade_frontalface_default.xml') img = cv2.imread(filename) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: img = cv2.rectangle(img, (x, y), (x+w, y+w), (255, 0, 0), 2) cv2.namedWindow('Vikings Detected!!') cv2.imshow('Vinkings Detected', img) cv2.imwrite('/home/utryjc/Pictures/viking.jpg', img) cv2.waitKey(0) detect(filename)
剛開始把gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)寫成了gray = cv2.cvtColor(img, cv2.COLOR_BAYER_BG2BGR)
出現問題:OpenCV Error: Assertion failed (scn == 1 && (dcn == 3 || dcn == 4)) in demosaicing, file /tmp/binarydeb/ros-kinetic-opencv3-3.3.1/modules/imgproc/src/demosaicing.cpp, line 1651
Traceback (most recent call last):
將參考書中的 img = cv2.imread(filename)改爲img = cv2.imread(filename, 0)即可