Save Image to Specified File using OpenCV

Save Image to Specified File using OpenCV

While working with image processing, we might need to save an intermediate image or final resulting image to a specified file.

OpenCV provides the imwrite function that allows to save an image to a file. Image format is determined using filename extension.

import cv2

img = cv2.imread('test.jpg')
grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cv2.imwrite('gray.jpg', grayImg)
#include <opencv2/opencv.hpp>

using namespace cv;

int main()
{
    Mat img = imread("test.jpg");
    Mat grayImg;
    cvtColor(img, grayImg, COLOR_BGR2GRAY);

    imwrite("gray.jpg", grayImg);

    return 0;
}
package app;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class Main
{
    static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }

    public static void main(String[] args)
    {
        Mat img = Imgcodecs.imread("test.jpg");
        Mat grayImg = new Mat();
        Imgproc.cvtColor(img, grayImg, Imgproc.COLOR_BGR2GRAY);

        Imgcodecs.imwrite("gray.jpg", grayImg);

        System.exit(0);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.