I want to execute the following code on a set of .jpg files, but always get an error when about a single-segmented buffer object.
code:
import cv2
import cv2.cv as cv
import os
import numpy as np
import fnmatch
def foo(directory):
cascade = cv2.CascadeClassifier("data/haarcascade_frontalface_alt.xml")
#loop through all files
for filename in fnmatch.filter(os.listdir(directory),'*.jpg'):
file_in = directory+"/"+filename
file_out= directory+"2/"+filename
img = cv2.imread(file_in)
#do face detection
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
rects = cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags = cv.CV_HAAR_SCALE_IMAGE)
rects[:,2:] += rects[:,:2]
rects = rects[0,:]
#crop image to the rectangle and resample it to 100x100 pixels
crop = img[rects[1]:rects[3],rects[0]:rects[2],:]
result = np.ndarray(shape=(100,100,3), dtype=np.uint8)
cv.Resize(cv.fromarray(crop),cv.fromarray(result))
cv2.imwrite(file_out, result)
cv2.destroyAllWindows()
Error:
File "foo.py", line 15, in foo
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
TypeError: expected a single-segment buffer object
What is wrong with this piece of code and how I can solve this error?
img
probably, and probably because image for some reason does not give a contiguous buffer through the python buffer interface. So you should probably check whyimg
is not a contiguous buffer. – seberg Apr 9 '13 at 11:25img
the first time: the first time python walks through the for loop, no error is thrown and the file is written out correctly. The error only happens the second time. – CommuSoft Apr 9 '13 at 23:47img = np.ascontiguousarray(img)
. You could also provideimg.flags
,img.strides
,img.shape
andimg.itemsize
if that does not do it (then you would be using a weird numpy version maybe, but would interest me if that has an effect). – seberg Apr 10 '13 at 7:20crop = (img[rects[1]:rects[3],rects[0]:rects[2],:]).copy()
. I think the reason is that numpy uses a lazy copy mechanims and doesn't know what to do when the source is rewritten. – CommuSoft Apr 14 '13 at 9:23