I have captured an image with my webcam using the following code:
cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CaptureFromCAM(0)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 960)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 544)
def record():
frame = cv.QueryFrame(capture)
cv.ShowImage("w1", frame)
splitter(frame, 4)
I’m trying to crop it into smaller pieces with cv.GetSubRect:
def splitter(image, split):
width, height = cv.GetSize(image)
x = width/split
y = height/split
# Form the 4-tuples.
img_parts = []
for y_pos in range(split):
for x_pos in range(split):
xy_section = (x_pos*x, y_pos*y, (x_pos+1)*x, (y_pos+1)*y)
# print xy_section
img_parts.append(xy_section)
# The cropping.
cropped_parts = []
for part in img_parts:
# print "part "+str(part)
cropped = cv.GetSubRect(image, part) # Error is thrown here
cropped_parts.append(cropped)
But I keep getting the error message
OpenCV Error: Incorrect size of input array () in cvGetSubRect, file
/build/buildd/opencv-2.3.1/modules/core/src/array.cpp, line 1262
The captured image’s size is 960×544, and I am splitting it with a list of 4-tuples, of which here are the first four:
- (0, 0, 240, 136)
- (240, 0, 480, 136)
- (480, 0, 720, 136)
- (720, 0, 960, 136)
The rectangles are taken in that order, and the error is thrown when trying to get the rectangle of the third 4-tuple, (480, 0, 720, 136). The original image is bigger than that (960×544), so what’s going wrong? An identical approach worked in Python’s PIL using image.crop(), but opencv’s alternative seems to work a little bit differently, I just can’t figure out how?
Opencv’s .GetSubRect() works a little bit differently from PIL’s .crop(). Both take as an argument a 4-tuple but they describe the area to be cropped differently.
PIL .crop():
For example in a 100×100 sized image (0, 50, 50, 100) crops exactly the bottom left corner of the image, resulting in a 50×50 sized image.
Opencv .GetSubRect():
For a same sized image 100×100, (0, 50, 50, 100) would crop a 50×100 sized area starting from position (0, 50) of the original image. The original image size is exceeded this way and the error is thrown. To crop the bottom left corner, (0, 50, 50, 50) works.