11

I am generating thumbnails for mp4 videos using the following code:

import cv2 as cv
from PIL import Image 

vidcap = cv.VideoCapture(videoPath)
vidcap.set(cv.CAP_PROP_POS_MSEC, millisecond)

#Turn video frame into numpy ndarray
success, image = vidcap.read()
cv.imwrite('fromImage.jpg', image)   #line to be replaced

The thumbnail generated from a high budget, professionally shot video looks like this: enter image description here Unfortunately in my application context, I will not be able to write the image frame directly to a file. Instead I must convert the image array generated by cv into a PIL image and then go from there. It looks something like this:

# Turn numpy ndarray int PIL image
img = Image.fromarray(image)
img.save('fromArray.jpg')    #Saving it for stackoverflow

But the outputted thumbnail from the same mp4 video is completely distorted as it seems to have swapped red and blue and looks like this:enter image description here Who or what is the culprit in this image distortion?

3
  • having the same issue Commented Jun 9, 2020 at 22:58
  • 1
    It seems, that RGB is interpreted as BGR, so read and blue color components are swapped. either you have to change the byte order or there is a parameter so say whether you have RGB or BGR Commented Jun 9, 2020 at 23:02
  • Agree with @gelonida. PIL treats and expects images in the normal, RGB order. But OpenCV expects and requires them to be in order of BGR. Commented Jun 9, 2020 at 23:37

1 Answer 1

22

https://note.nkmk.me/en/python-opencv-bgr-rgb-cvtcolor/

imageRGB = cv.cvtColor(image, cv.COLOR_BGR2RGB)

img = Image.fromarray(imageRGB)

img.save('fromArray.jpg')
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, this works

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.