我正在使用连接到Raspberry Pi 2型号B的网络摄像头拍摄照片。然后,我检测到照片中的脸部并裁剪脸部并将其另存为单独的图像。以下代码在Windows中完美运行。
import numpy as np
import cv2
import math
from random import random
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
ret,frame = cap.read()
#naming the image and save path
img_name = str(int(math.ceil(100000*random())))
img_path = 'images/'+img_name+'.png'
crop_img_path = 'images/'+'crop_'+img_name+'.png'
# directly saving the image
cv2.imwrite(img_path,frame)
cap.release()
img = cv2.imread(img_path) #read image to numeric array
#printing image information
print str(img.shape) + " "
print str(img.size) + " "
print str(img.dtype)
#detecting face
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
face_cascade.load('haarcascade_frontalface_default.xml')
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) # drawing rectangle (Blue, thickness 2)
print str(x)+" "+str(y)+" "+str(x+w)+" "+str(y+h) #printing region coordinates of rectangle
crop_img = img[y:y+h,x:x+w]
cv2.imwrite(crop_img_path,crop_img)
但它在Raspbian中给出了以下错误:
Traceback (most recent call last):
File "xyz.py", line 35, in <module>
crop_img = img[y:y+h,x:x+w]
TypeError: 'NoneType' object has no attribute '__getitem__'
注1:原始拍摄的图像保存在images文件夹中。
注2:我使用follow命令安装了OpenCV for Python:
sudo apt-get install python-opencv
答案 0 :(得分:2)
你的问题就在这一行:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
此处您将img
重新分配给None
,以免丢失原始对象。
参考OpenCV2 documentation,cv2.rectangle
返回None
。
因此,
crop_img = img[y:y+h,x:x+w]
会显示错误消息
矩形
绘制一个简单,厚实或填充右上方的矩形。
C ++:void rectangle(Mat&amp; img,Point pt1,Point pt2,const Scalar&amp; color,int thickness = 1,int lineType = 8,int shift = 0)
C ++:void rectangle(Mat&amp; img,Rect rec,const Scalar&amp; color,int thickness = 1,int lineType = 8,int shift = 0)
Python:cv2.rectangle(img,pt1,pt2,color [,thickness [,lineType [, shift]]])→无
C:void cvRectangle(CvArr * img,CvPoint pt1,CvPoint pt2,CvScalar color,int thickness = 1,int line_type = 8,int shift = 0)
Python:cv.Rectangle(img,pt1,pt2,color,thickness = 1,lineType = 8, shift = 0)→无
为了修复您的代码,您不应该重新分配img
,而应该执行以下操作:
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) # drawing rectangle (Blue, thickness 2)
print str(x)+" "+str(y)+" "+str(x+w)+" "+str(y+h) #printing region coordinates of rectangle
crop_img = img[y:y+h,x:x+w]
cv2.imwrite(crop_img_path,crop_img)