Getting garbage image using VideoCapture in Raspberry Pi

I am using the following code to get images from the Raspberry Pi 4 camera (Pi Camera V2, OpenCV 4.5):

#include <opencv2/opencv.hpp>

using namespace cv;

const int VID_HEIGHT = 1232;
const int VID_WIDTH = 1640;

// const int VID_HEIGHT = 720;
// const int VID_WIDTH = 1280;

int main(){
    Mat image;
    VideoCapture cap(0);


    if(!cap.isOpened()) {
        return -1;

    imwrite("test1.jpg", image); 
    return 0;

The problem is, when the image width and height are set to 1640x1232, it writes a garbage image in the file (test1.jpg), shown below:

But if the image width and height are set below 1280x720, the images are correct in the given file. How to fix this problem? I want to use the resolution 1640x1232 because it uses the full FOV of the PI camera.

IIRC it requires that you request a larger (or smaller?) size because it has to be a multiple of something, or it’s automatically rounded up…

play around with the width until the picture looks okay.

1 Like


One thing I found that, the FOV of the opencv images of resolution 640x480 is same as the FOV of an raspistill image in 8MP. Does that mean opencv does not follow the FOV of PI camera as described here: 6. Camera Hardware — Picamera 1.12 documentation?

I wouldn’t know. when you ask for device 0, OpenCV merely uses /dev/video0 via V4L API