conversion from opencv image to jpeg image in python

Question:

I’m grabbing frames from a video file as following:

def capture_frame(file):
        capture = cv.CaptureFromFile("video.mp4")
        cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_POS_MSEC)
        cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_POS_MSEC, 90000)
        frame = cv.QueryFrame(capture)
        return frame

The frame type is cv2.cv.iplimage. How can I convert this type of image to jpeg image without saving?

Thanks,

Asked By: yusuf

||

Answers:

Did you try just writing chunks?

with open('filename.jpeg', 'wb+') as destination:
            for chunk in image_file.chunks():
                destination.write(chunk)
 

Here’s one worth looking at too that uses opencv natively http://answers.opencv.org/question/115/opencv-python-save-jpg-specifying-quality-gives-systemerror/. Although, not sure why you’re trying to save .mp4 to .jpeg

Answered By: AndrewSmiley

The following should give you the bytes for a jpeg representation of the image.

def capture_frame(file):
        capture = cv.CaptureFromFile(file)
        cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_POS_MSEC)
        cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_POS_MSEC, 90000)
        frame = cv.QueryFrame(capture)
        return cv.EncodeImage('.jpg', frame).tostring()

capture_frame("video.mp4")

I’ve written out the results of EncodeImage to a file opened in binary (open('somefile','wb')) which resulted in a valid JPEG.

Answered By: djsumdog
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.