OpenCV image processing - create, read, and save images losslessly (C++/Python)

1. Create images

C++

#include <opencv2/opencv.hpp>

int main() 
{
    
    
    int width = 640;  // 图像宽度
    int height = 480; // 图像高度

    // 创建一个空白的黑色图像
    cv::Mat blank_image(height, width, CV_8UC3, cv::Scalar(0, 0, 0));
    
    // 显示图像
    cv::imshow("Blank Image", blank_image);
    cv::waitKey(0);

    return 0;
}

Python

import cv2
import numpy as np

width = 640  # 图像宽度
height = 480  # 图像高度
channels = 3  # 颜色通道数
imgEmpty = np.empty((height, width, channels), np.uint8)  # 创建空白数组
imgBlack = np.zeros((height, width, channels), np.uint8)  # 创建黑色图像 RGB=0
imgWhite = np.ones((height, width, channels), np.uint8) * 255  # 创建白色图像 RGB=255

2. Read the image

C++

Read image function
Mat imread(const String& filename, int flags = IMREAD_COLOR)
This function loads the image from the specified file and returns it as a Mat object. If the function cannot read the file, it returns an empty Mat object.
filename - A relative or absolute path to the image file must be provided. If you provide a relative path, it should be relative to your cpp file. jpeg, jpg, bmp, png, tiff and tif image file types are always supported. Additional image file types are supported depending on your platform and installed codecs.

flags - The flag parameter has several possible values. Use the default IMREAD_COLOR parameter.

  • IMREAD_UNCHANGED - the image will be loaded as-is. If you want to get the alpha channel in your input image (if it is available), you must use this flag.
  • IMREAD_GRAYSCALE - the image will be loaded as a grayscale image (i.e. - single channel image, black and white image)
  • IMREAD_COLOR - image will be loaded as BGR image (ie - 3 channel image, color image)
#include <opencv2/opencv.hpp>

int main() 
{
    
    
    // 读取图像文件
    cv::Mat image = cv::imread("image.jpg", cv::IMREAD_COLOR);

    if (image.empty()) 
    {
    
    
        std::cerr << "Image not found!" << std::endl;
        return -1;
    }

    // 显示图像
    cv::imshow("Loaded Image", image);
    cv::waitKey(0);

    return 0;
}

Python

The same goes for the python version’s reading parameters.

import cv2

# 读取图像文件
image = cv2.imread('image.jpg')

if image is None:
    print('Image not found!')
else:
    # 显示图像
    cv2.imshow('Loaded Image', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

3. Save the image

C++

When using opencv to do some image processing operations, you need to save some high-resolution images. For example, you need to process an image with an operating size of 275M and save the processed image.
The following picture is an example, the image size is 275M
Insert image description here

Insert image description here
Write a code to try the effect:

#include<opencv2\opencv.hpp>   

int main(int argc, char** argv)
{
    
    
	cv::Mat cv_src = cv::imread("big.png");

	cv::imwrite("save_as_jpg.jpg", cv_src);

	return 0;
}

After saving the picture, open the image and take a look. It is compressed to only 44M.
Insert image description here

Here, because it is saved as JPG, the image format is compressed. The JPG image format has its own compression, while the bmp format image does not have any compression.
If you want to save high-quality JPG, you can take a look at the imwrite prototype:

CV_EXPORTS_W bool imwrite( const String& filename, InputArray img, const std::vector& params = std::vector()); The third parameter
description: params of const std::vector& type, indicating the parameter encoding saved in a specific format, It has a default value of std::vector(), so generally there is no need to fill it in. If changed, different image formats will have different corresponding values ​​and different functions.

For images in JPEG format, this parameter represents the image quality from 0-100 (CV_IMWRITE_JPEG_QUALITY). The default value is 95.

#include<opencv2\opencv.hpp>   

int main(int argc, char** argv)
{
    
    
	cv::Mat cv_src = cv::imread("big.png");

	std::vector<int> compression_params;
	compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);  //选择jpeg
	compression_params.push_back(100); //在这个填入你要的图片质量

	cv::imwrite("save_as_jpg.jpg", cv_src,compression_params);

	return 0;
}

Insert image description here
After parameter adjustment, the size compression of images saved in jpg format is not that severe. However, saving pictures in jpg format still cannot save 100% of the original image!
After a picture in jpg format is read into the memory and then saved in jpg format, the capacity will be compressed. This is a characteristic of the jpg format. No matter how you adjust the compression ratio, distortion (loss of picture quality) cannot be avoided.

If you want to save an image in PNG format, the parameter indicates the compression level (CV_IMWRITE_PNG_COMPRESSION) from 0-9, higher values ​​mean smaller size and longer compression time and the default value is 3.

#include<opencv2\opencv.hpp>   

int main(int argc, char** argv)
{
    
    
	cv::Mat cv_src = cv::imread("big.png");
	std::vector<int> compression_params;
	compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION); //PNG格式图片的压缩级别  
	compression_params.push_back(9);  //这里设置保存的图像质量级别

	cv::imwrite("save_as_png.png", cv_src,compression_params);

	return 0;
}

Judging from the saving results, when saving in PNG format, the quality of the saved image is closest to the original quality, but the writing speed is the slowest:
Insert image description here

Python

cv_src = cv2.imread("face.jpeg")
cv2.imwrite('save_as_png.png', cv_src, [cv2.IMWRITE_PNG_COMPRESSION, 9])
cv2.imwrite('save_as_jpg.jpg', cv_src, [cv2.IMWRITE_JPEG_QUALITY, 99])
BMP format (no compression):

BMP is an uncompressed image file format with no loss of image data, so file sizes are often large. It is a hardware-independent format that can be used to store high-quality image data, but it takes up more disk space relative to other formats. BMP is suitable for storing images with high bit depth and no need for compression, such as bitmaps or temporary files during image editing.

JPEG format (lossy compression):

JPEG is a lossy compression format suitable for compressing images to a relatively small file size, but with the loss of some image detail and quality. It is commonly used to store photos and other images that require high compression ratios to reduce file size, but can result in noticeable quality loss at too high a compression ratio. The JPEG format has the function of adjusting image quality, allowing you to make a trade-off between image quality and file size.

PNG format (lossless compression):

PNG is a lossless compression format that retains the high quality of images without losing detail. It supports true color images and transparency channels, and is suitable for situations where image quality needs to be maintained and a transparent background is desired to be preserved. Although PNG file size is generally larger than JPEG, it is more reliable at maintaining image quality and is suitable for applications such as image editing and web graphics that require high quality.

Guess you like

Origin blog.csdn.net/matt45m/article/details/133162043