Image Orientation (python+openCV)
Asked Answered
A

2

12

Using Python and OpenCV, I try to read an image which size is (3264*2448), but the resulting size is always (2448*3264). That means the direction of the image is changed by 90 degrees. The code is following:

img1 = cv2.imread("C:\\Users\\test.jpg", 0) 
cv2.namedWindow("test", 0) 
cv2.imshow("test", img1)

the orignal image is this:

enter image description here

but I get this image:

enter image description here

Africander answered 14/6, 2017 at 6:29 Comment(1)
looking at the exif information of the image file. Do you see an "Orientation" information?Hypersensitize
R
14

I faced a similar issue in one program. In my case, the problem was due to the camera orientation data stored in the image.

The problem was resolved after I used CV_LOAD_IMAGE_COLOR instead of CV_LOAD_IMAGE_UNCHANGED in OpenCV Java.

Rat answered 11/8, 2017 at 8:58 Comment(4)
Thanks, I had the reverse issue. I had to prevent opencv from rotating. You answered helped me find the right way of doing that. I ended up use:cv2.imread(name, cv2.IMREAD_IGNORE_ORIENTATION | cv2.IMREAD_COLOR)Greed
This should be added as an answer!Streamer
Adding to @Greed reply, cv2.IMREAD_LOAD_GDAL instead of cv2.IMREAD_IGNORE_ORIENTATION also works.Leekgreen
Keep in mind that cv2.IMREAD_COLOR will convert the image to 3 channels RGB, so if you need transparency, it won't work.Encroach
D
6

OpenCV only applys EXIF 'Orientation' tags with an OpenCV version >= 3.1. If you are stuck with a lower version and PIL is available:

import PIL, cv2, numpy

path = 'test.jpg'
pix = PIL.Image.open(path) 
# get correction based on 'Orientation' from Exif (==Tag 274)
try:
    deg = {3:180,6:270,8:90}.get(pix._getexif().get(274,0),0)
except:
    deg = 0
if deg != 0:
    pix=pix.rotate(deg, expand=False)
# convert PIL -> opencv
im0 = numpy.array(pix)
if len(im0.shape)==3 and im0.shape[2] >= 3:
    # fix bgr rgb conventions
    # note: this removes a potential alpha-channel (e.g. if path point to a png)
    im0 = cv2.cvtColor(im0, cv2.COLOR_BGR2RGB) 
Dubose answered 28/2, 2019 at 16:10 Comment(1)
Note that PIL can do it automagically now pillow.readthedocs.io/en/stable/reference/…Pow

© 2022 - 2024 — McMap. All rights reserved.