1
votes

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!

3
show your code.Geancarlo Murillo
Would like to see the coding bit as well!72133185
@GeancarloMurillo ...and your data. See: minimal reproducible example.AMC
Thanks for the suggestions. The data is private. As for code, I just used 2 lines: img = cv2.imread(file_path) cv2.imwrite(new_file_path, img)Kenny

3 Answers

2
votes

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.

0
votes

I had a similar problem when saving frame images using cv2.imwrite() when reading a video file using cv2.VideoCapture(). It was due to OpenCV not properly reading video orientation/rotation meta data. This was still an issue for me even with OpenCV 4.

I ended up using scikit-video - a Python wrapper around ffmpeg. No more rotation issues: http://www.scikit-video.org/stable/io.html

0
votes

One possible solution is to change cv2.IMREAD_UNCHANGED to cv2.IMREAD_COLOR while loading image with imdecode. From some reason "unchanged" is not able to read EXIF metadata correctly