2016-04-30 54 views
1

我使用下面的代碼來檢測人臉:Python的 - 調整圖像

import io 
import picamera 
import cv2 
import numpy 
import PIL 
from PIL import Image 
from resizeimage import resizeimage 

#Load a cascade file for detecting faces 
face_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml') 

#Create a memory stream so photos doesn't need to be saved in a file 
stream = io.BytesIO() 

#Get the picture (low resolution, so it should be quite fast) 
#Here you can also specify other parameters (e.g.:rotate the image) 
with picamera.PiCamera() as camera: 
    camera.resolution = (640, 480) 
    camera.vflip = False 
    camera.hflip = False 
    camera.brightness = 60 
    camera.capture(stream, format='jpeg') 

#Convert the picture into a numpy array 
buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8) 

#Now creates an OpenCV image 
image = cv2.imdecode(buff, 1) 

#Load a cascade file for detecting faces 
#face_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml') 

#Convert to grayscale 
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) 

#Look for faces in the image using the loaded cascade file 
faces = face_cascade.detectMultiScale(gray, 1.1, 5) 

print "Found "+str(len(faces))+" face(s)" 

#Draw a rectangle around every found face 
#Crop faces and save to separate files 
id = 1 
for (x,y,w,h) in faces: 
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2) 
    cropped = image[ y : y+h, x : x+w ] 
    #RESIZE IMAGE to 92x112 
    cropped = cv2.resize(cropped,None,92,112) 
    cv2.imwrite("../reco/test_faces/cropped_face" + str(id) + ".png", cropped) 
    id = id + 1 

當時我想的面裁剪成圖像文件,並將其調整爲92x112結束。這是我嘗試用

cropped = cv2.resize(cropped,None,92,112) 

當我運行此我得到

OpenCV的錯誤:調整大小斷言失敗(dsize.area()||(inv_scale_x> 0 & & inv_scale_y> 0)),文件/build/opencv-ISmtkH/opencv-2.4.9.1+dfsg/modules/imgproc/src/imgwarp.cpp,第1835行 回溯(最近一次調用最後一次): 文件「1track.py」,第48行,在 裁剪= cv2.resize(裁剪,無,92,112) cv2.error:/build/opencv-ISmtkH/opencv-2.4.9.1+dfsg/modules/imgproc/src/imgwarp.cpp:1835:error:(-215) dsize.area()|| (inv_scale_x> 0 & & inv_scale_y> 0)in function resize

任何幫助都會很棒。 對不起,如果th的問題是愚蠢的,我是一個絕對的初學者在編程,上面的代碼是一個谷歌搜索結果.. 謝謝!

回答

0

要將圖像調整到新的尺寸,您需要知道新尺寸和當前尺寸之間的比例。所以,如果你想設置(例如)640×480的圖像爲92x112形象:

六百四十○分之九十二= 0.143 四百八十零分之一百十二= 0.233

您在cv2.resize功能使用這些比:

cropped = cv2.resize(cropped, (0,0), fx=0.143, fy=0.233)