OpenCV implements photo background color processing

Table of contents

1. Introduction

2. Introduction

3. Code analysis

4. Optimization and improvement

5. Summary


1. Introduction

In the field of image processing, OpenCV is a powerful and widely used open source library that can provide rich image processing and computer vision functions. This blog will introduce how to use the Qt editor to call the OpenCV library to change the background color of photos to achieve more unique and attractive effects

The final implementation effect is as follows

2. Introduction

OpenCV is a cross-platform computer vision library that contains a large number of functions and algorithms for image processing. Photo background color processing is a common image processing technology, which can be applied to advertising design, photography post-processing and other fields to add more artistic expression to photos. This blog will use the functions and methods in the OpenCV library to replace the background within the specified color range with a custom color in a photo.

3. Code analysis

Photo color changer is an image processing technique that changes the overall visual effect of a photo by selecting and replacing the background color. The OpenCV library provides a wealth of functions and methods, which can realize operations such as reading, processing and displaying images. By using OpenCV's functions such as color conversion, color range selection, and image copying, we can easily implement photo background color processing.

1. First, you need to introduce the header file of the OpenCV library in the program , so that you can use the functions and data structures of OpenCV. First download OpenCV and then include the OpenCv header file into the pro file to pay attention to find the address of the include file

Then in the bin file in x86, the files shaped like libopencv_*, dll are included and copied and pasted to C:\Windows\SysWOW64

 After adding the library, the header file should also be included (you can run it before adding the OpenCV header file, otherwise the computer may not be able to find the library, let the computer react)

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

 2. Process the picture

In the code used this time, we first convert the input image to HSV format in order to better handle the color information. Then, by specifying a range of colors, a mask is created that sets pixels within the range to white and pixels outside the range to black. Next, through the inversion operation, we can extract the portrait area from the original image. Create a new background image and set it to a custom background color. Finally, by copying the original image into a new background image, only the portrait area is preserved, achieving the effect of changing the background color of the photo.

Code

    //1.显示一张图片
    Mat image = imread("d:/test.png");
    imshow("1",image);

    //2.图片转hsv格式
    Mat hsv;
    cvtColor(image,hsv,COLOR_BGR2HSV);
    imshow("2",hsv);

    //3.截取颜色区域的范围 inRang   在hsv取值范围内 呈白色  不在范围内 呈黑色
    Mat mask;//模板
    inRange(hsv,Scalar(100,43,46),Scalar(124,255,255),mask);
    imshow("3",mask);//现在的mask 就是可以抠出蓝色的底色

    //4.取反操作  但是我们需要抠出的是人像
    bitwise_not(mask,mask);
    imshow("4",mask);

 Perform hsv on the picture, select color, and invert to create a new background. The effect is as follows

Scalar can select the color range, the three-element RGB color range, and refer to the hsv table for the selected color

 3. Change the background color of the photo and choose a red background

The red background RGB selection is 40, 40, 200, and the range can also be adjusted according to your needs

 //5.做一张红色背景图   大小?类型? 参考image原始图片
    Mat redBack = Mat::zeros(image.size(),image.type());
    redBack = Scalar(40,40,200);
    imshow("5",redBack);

    //6.实现图片的拷贝操作
    image.copyTo(redBack,mask);
    imshow("6",redBack);

4. Optimization and improvement

For the original code, we can make some optimizations and improvements to improve the readability and scalability of the code. For example, the function of changing the background color can be encapsulated into an independent function, which is convenient for repeated calls. At the same time, the function can be customized according to different needs through parameterization. In addition, error checking and exception handling mechanisms can be added to improve the robustness and fault tolerance of the code. In addition, after optimization, the process of saving images is also added

Complete code after optimization

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

void changeBackground(const Mat& inputImage, const Scalar& backgroundColor, const Scalar& lowerBound, const Scalar& upperBound)
{


    // 图片转为hsv格式
    Mat hsv;
    cvtColor(inputImage, hsv, COLOR_BGR2HSV);
    // 在指定范围内的变为白色,不在范围内的变为黑色
    Mat mask;
    inRange(hsv, lowerBound, upperBound, mask);
    imwrite("D:/QtProject/mask1.png", mask);

    // 取反操作,抠出人像
    bitwise_not(mask, mask);


    // 创建新的背景图像
    Mat newBackground = Mat::zeros(inputImage.size(), inputImage.type());
    newBackground = backgroundColor;

    // 将原始图像复制到新背景图像中,只保留前景(人像)区域
    inputImage.copyTo(newBackground, mask);

    imshow("New Background Image", newBackground);


    //保存图片
    imwrite("D:/QtProject/new_background.png", newBackground);


}

int main(int argc, char* argv[])
{
    // 显示一张图片
    Mat image = imread("D:/QtProject/gege.jpg");
    imshow("1",image);
    // 检查图像是否成功加载
    if (image.empty())
    {
        cout << "Failed to load image." << endl;
        return -1;
    }

    // 定义背景颜色、颜色范围
    Scalar backgroundColor(60,60,220);
    Scalar lowerBound(100, 43, 46);
    Scalar upperBound(124, 255, 255);

    // 更换背景
    changeBackground(image, backgroundColor, lowerBound, upperBound);

    // 等待用户按下任意键
    waitKey(0);

    return 0;
}

5. Summary

Through this blog, we have learned about the method and steps of OpenCV to realize photo background color processing. The OpenCV library provides a wealth of image processing functions and algorithms that can help us achieve a variety of image processing tasks. Photo background color changer is one of them. By selecting and replacing the background color, you can add unique artistic effects to photos. I hope this blog can help readers understand and apply the OpenCV library for image processing. If there are students who need to download Qt and OpenCV, you can chat with me privately. Welcome everyone to make progress together.

Guess you like

Origin blog.csdn.net/qq_64691289/article/details/131839345