I am currectly using opencv to obtain image size of different image, but i have encounter some problem. Sometimes the width data mixed up with the height data for some reason. Here is a example:
1st example Image size: 2988 * 5312 height: 5312 width: 2988
OpenCV data: (2988,5312,3)
2nd example Image size: 4160 * 3120 height: 3120 width: 4160
OpenCV data: (3120,4160,3)
As you can see from this two example, their width and height are in different slot in the tuple. But from what i search online, img.shape[0] should represent height, img.shape[1] should represent width. But in example 1, the width and height seems mixed up. How can i fix this problem? Anyone can explain whats happening here and anyways to make it show in same way for all photo.
CodePudding user response:
I imagine OpenCV is looking at the "EXIF Orientation" field. You can disable that with:
im = cv2.imread(filename, cv2.IMREAD_COLOR|cv2.IMREAD_IGNORE_ORIENTATION)
You can check the orientation easily in your Terminal with exiftool
:
exiftool YOURIMAGE
CodePudding user response:
The issue you are experiencing is that the width and height data are being swapped when you read the image using OpenCV's 'imread()' function. This can happen if the image file has been saved with the width and height data stored in the wrong order.
To fix this issue, you can simply check which of the two values is larger and use that as the width and the other as the height. Here is an example of how you can do this:
height, width = img.shape[:2]
if height > width:
height, width = width, height
This will swap the values of height and width if height is larger than width. This way, you can be sure that the width value is always the larger of the two, regardless of the order in which they were stored in the image file.
Note that this issue can also occur if the image has been rotated and saved with the width and height data stored in the wrong order. In this case, you can use the rotate() function from OpenCV's 'imutils' module to fix the orientation of the image before processing it.
import imutils
# Rotate the image if necessary
if height > width:
img = imutils.rotate(img, 90)
# Continue processing the image as normal