问题
I'm using cv2.rectangle in python to draw a box on my image.
image1 has already been loaded correctly.
Then I use this code:
cv2.rectangle(image1, (10, 10), (100, 100), (255,0,0), 2)
cv2.imshow('img', image1)
But I get this error:
TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)
I get errors no matter what I do with the image after using cv2.rectangle. How can I retrieve or use the image on which I drew the rectangle?
Edit
Correction, I get this error on using cv2.rectangle, not after it.
回答1:
Heh, several years late to help the original poster, but I just hit this problem myself and didn't have control over the image source (so cv2.imread wasn't a great solution for me - I'd've had to have written the image back to disk first).
I was able to proceed with image = image.copy().
Not sure what the root cause was - an equality check showed every value of the array was equivalent, and the array was the correct type. ¯\_(ツ)_/¯
回答2:
This code should do what you want:
import cv2
im = cv2.imread('<path to image>')
cv2.rectangle(im, (10, 10), (100, 100), (255,0,0), 2)
im = cv2.cv.fromarray(im)
cv2.cv.SaveImage("<path you want to save image in>", im)
回答3:
This issue appears to be caused by the version of numpy. Version 1.6.2 seems to cause this bug, but this issue is not present in 1.9.2, just upgrade it:
pip install numpy --upgrade
Tested on Debian 7.8 (kern 3.2) and Debian 8.0 (kern 4.2) for OpenCV 2.4.9
来源:https://stackoverflow.com/questions/23723369/using-image-with-rectangle-drawn-over-it-in-python