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

ForceBru
  • 43,482
  • 10
  • 63
  • 98
yuanyesjtu
  • 121
  • 1
  • 1
  • 5
  • 3
    looking at the exif information of the image file. Do you see an ["Orientation"](http://sylvana.net/jpegcrop/exif_orientation.html) information? – Shai Jun 14 '17 at 07:20

2 Answers2

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
  • 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)` – oak Feb 15 '18 at 17:55
  • This should be added as an answer! – ClimbingTheCurve Jun 16 '19 at 13:46
  • Adding to @oak reply, `cv2.IMREAD_LOAD_GDAL` instead of `cv2.IMREAD_IGNORE_ORIENTATION ` also works. – mrbTT Nov 01 '19 at 19:56
  • Keep in mind that cv2.IMREAD_COLOR will convert the image to 3 channels RGB, so if you need transparency, it won't work. – William Dias Apr 13 '22 at 17:46
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) 
Oliver Zendel
  • 2,695
  • 34
  • 29
  • Note that PIL can do it automagically now https://pillow.readthedocs.io/en/stable/reference/ImageOps.html?highlight=Exif_tr#PIL.ImageOps.exif_transpose – Mark Setchell Feb 14 '22 at 08:25