Incorrect image orientation when drawing a line with cv2.line
Question:
I want to draw a line from top left corner to the bottom right corner on an image.
The image is horizontal and:
print(size)
returns:
(203, 248)
With my code I am expecting a diagonal line from pixel (0,0) to pixel (203, 248). However I am getting diagonal line from pixel (0,0) to pixel (248, 203) which is outside the image boundary (sic!).
I suppose the cv2.line
method rotates the image somehow, can anyone advise?
Here is my code:
import cv2
image_1 = cv2.imread('profilowe.jpeg',0)
size = image_1.shape
print(size)
cv2.line(image_1,(0,0),image_1.shape,255,1,16)
cv2.imshow('image',image_1)
cv2.waitKey(0)
cv2.destroyAllWindows()
Answers:
This happens because while NumPy indexes arrays based on a row-first principle (i.e. your shape is (rows, columns)), OpenCV indexes based on (x, y) co-ordinates, meaning the axes are flipped. This can be annoying to deal with, but this should fix your issue:
Try changing:
cv2.line(image_1, (0,0), image_1.shape, 255, 1, 16)
to
cv2.line(image_1, (0,0), image_1.shape[::-1], 255, 1, 16)
The [::-1]
flips the tuple to become (248, 203)
, and your line should look fine now.
I want to draw a line from top left corner to the bottom right corner on an image.
The image is horizontal and:
print(size)
returns:
(203, 248)
With my code I am expecting a diagonal line from pixel (0,0) to pixel (203, 248). However I am getting diagonal line from pixel (0,0) to pixel (248, 203) which is outside the image boundary (sic!).
I suppose the cv2.line
method rotates the image somehow, can anyone advise?
Here is my code:
import cv2
image_1 = cv2.imread('profilowe.jpeg',0)
size = image_1.shape
print(size)
cv2.line(image_1,(0,0),image_1.shape,255,1,16)
cv2.imshow('image',image_1)
cv2.waitKey(0)
cv2.destroyAllWindows()
This happens because while NumPy indexes arrays based on a row-first principle (i.e. your shape is (rows, columns)), OpenCV indexes based on (x, y) co-ordinates, meaning the axes are flipped. This can be annoying to deal with, but this should fix your issue:
Try changing:
cv2.line(image_1, (0,0), image_1.shape, 255, 1, 16)
to
cv2.line(image_1, (0,0), image_1.shape[::-1], 255, 1, 16)
The [::-1]
flips the tuple to become (248, 203)
, and your line should look fine now.