Search code examples
pythonimageopencvpngjpeg

opencv imwrite, image get rotated


I am using opencv in python (cv2) to do some processing on images with format jpg, png and jpeg, JPG. I am doing a test that write image to disk using "cv2.imwrite" right after reading from "cv2.imread". I found part of the image get rotated, some of them rotate 90d, some rotate 180d. But most image keep the right orientation. I cannot conclude a pattern that causes this rotation. Anyone knows more details? Thanks!


Solution

  • It sounds like the EXIF orientation flag:

    Why Are My Images Wrongly Displayed?
    When you use a photo viewer to check the image on your computer, if the photo viewer can read the Exif info and respects that info, it will automatically rotate the raw image based on the orientation info. The end result is that you can see the correctly-oriented photo no matter how it is actually stored.

    Meaning the image looks correct when viewed on the desktop, because the file-info says 'rotate this image 90d before showing'. If your script doesn't read the EXIF info, it stores a new image, without the flag, so the image is displayed rotated.

    However, according to this answer opencv handles this automatically since version 3.1 . Is your openCV version current?

    Source article

    Update
    A comment in this question suggests you can't write exif data with openCV.
    You can also use exifread or PIL to get the exif data and rotate the image in your script.