Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

np.rot90() corrupts an opencv image

Tags:

python

opencv

When trying to rotate a landscape image to portrait, after applying the rotation, I cannot draw on the image.

img1 = cv2.imread('a.jpg')
cv2.circle(img1, tuple([10,10]),radius = 3, color = (255,0,0))

works fine.

Then I try:

img2 = np.rot90(img1,3)
cv2.circle(img2, tuple([10,10]),radius = 3, color = (255,0,0))

and I get the error:

TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)

Looking at type(img2) and img2.dtype it seems identical to img1. the dimensions also seem fine (the first two dimensions are flipped, the third stays "3")

BTW: this seems to work. (why?):

img2 = np.rot90(img1,3)
img3 = img2.copy()
cv2.circle(img3, tuple([10,10]),radius = 3, color = (255,0,0))
like image 881
eran Avatar asked Dec 30 '13 16:12

eran


People also ask

How do I rotate an image in OpenCV using NumPy?

Python's OpenCV handles images as NumPy array ndarray. There are functions for rotating or flipping images (= ndarray) in OpenCV and NumPy, either of which can be used. Here, the following contents will be described. Rotate image with OpenCV: cv2.rotate () Rotate image with NumPy: np.rot90 ()

What is rotation matrix in OpenCV?

OpenCV allows us rotation and scale at a time. we use Rotation matrix for image rotations. 90 indicates how much image is to rotate in a counter-clockwise direction and 1 is scale. Resizing images is one of the technics in OpenCV. This makes the image occupy less space in the disk. Interpolation is used for a better way of resizing images.

What is the difference between 9090 and 1 in OpenCV?

90 indicates how much image is to rotate in a counter-clockwise direction and 1 is scale. Resizing images is one of the technics in OpenCV. This makes the image occupy less space in the disk. Interpolation is used for a better way of resizing images.

What is an image in OpenCV?

It is stored as an array of pixels and can be a 2-D array (grayscale) and a 3-D array (simple grayscale image with three channels) while using images in OpenCV. Let’s get started with our agenda. We are going to draw a simple image of Hut with white background.


1 Answers

I had the same issue and never got to the bottom of it. The workaround I used was to do the image rotation/flipping with OpenCV instead, like:

# flip image vertically
img = cv2.flip(img, 0)

# flip image horizontally
img = cv2.flip(img, 1)

# transpose image
img = cv2.transpose(img)

Note that rotation is equivalent to doing a transpose and a flip.

like image 179
101 Avatar answered Oct 05 '22 04:10

101