search
HomeWeb Front-endPS TutorialThe road to growth of OpenCV (3): imitating the magic wand tool in PhotoShop

The subject of this article is actually the conversion of the color space of the image. With the help of a color selection program, the usage of the color conversion function in OpenCV and some precautions are explained.

1. Several common color spaces:

RGB color space: RGB uses the additive color mixing method, because it describes the ratio of various "lights" to produce colors. Starting from darkness, light continuously superimposes to produce color. RGB describes the values ​​of red, green and blue light. Digital image storage generally uses RGB mode. It is worth noting that the storage order of the three channels in OpenCV is BGR.

HSV, HSI: These two color formats are defined based on the human eye's distinction between colors, where H (hue) represents hue, S (saturation) represents saturation, and V (value) represents Lightness, I (intensity) represents brightness.

Lab space: Uniform changes in the model correspond to uniform changes in perceived color, so we can imagine Lab as a point in the color space. The closer the adjacent points are, the closer they are to each other. The closer, so Lab space is often used to measure the similarity of two colors.

For more knowledge about color space, please refer to: http://en.wikipedia.org/wiki/Color_space

2. Color space conversion in OpenCV

In OpenCV The color conversion of the image is completed through the cvtColor function. cvtColor is defined in the opencv2/imgproc/imgproc.hpp header file. Its C++ interface is as follows:

void cvtColor( InputArray src, OutputArray dst, int code, int dstCn=0 )

src: Input image.

dst: Output image.

code: Color conversion type, such as: CV_BGR2Lab, CV_BGR2HSV, CV_HSV2BGR, CV_BGR2RGB.

dstCn: The channel number of the output image. If the default is 0, it means the number of channels of the input image.

Convert the image image from BGR to Lab: cvtColor(image,image,CV_BGR2Lab)

3. Simple magic wand program

First we define a colorDetect class:

class colorDetect{private:    int minDist; //minium acceptable distance    Vec3b target;//target color;    
    Mat result; //the resultpublic:
    colorDetect();    void SetMinDistance(int dist);    void SetTargetColor(uchar red,uchar green,uchar blue);    void SetTargetColor(Vec3b color); //set the target color    Mat process(const Mat& image); //main process};

The minDist is the threshold we define to limit the distance between two colors, which is equivalent to the threshold of the magic wand tool in PhotoShop.

target is the target color, which is equivalent to the seed color. result is the result of storage processing.

Process is the main processing program. Let’s look at the content of process.

Mat colorDetect::process(const Mat& image)
{    Mat ImageLab=image.clone();
    result.create(image.rows,image.cols,CV_8U);    
    //将image转换为Lab格式存储在ImageLab中    
    cvtColor(image,ImageLab,CV_BGR2Lab);    
    //将目标颜色由BGR转换为Lab    
    Mat temp(1,1,CV_8UC3);
    temp.at<Vec3b>(0,0)=target;//创建了一张1*1的临时图像并用目标颜色填充    
    cvtColor(temp,temp,CV_BGR2Lab);
    target=temp.at<Vec3b>(0,0);//再从临时图像的Lab格式中取出目标颜色

    // 创建处理用的迭代器    
    Mat_<Vec3b>::iterator it=ImageLab.begin<Vec3b>();    
    Mat_<Vec3b>::iterator itend=ImageLab.end<Vec3b>();    
    Mat_<uchar>::iterator itout=result.begin<uchar>();    
    while(it!=itend)
    {        
    //两个颜色值之间距离的计算        
    int dist=static_cast<int>(norm<int,3>(Vec3i((*it)[0]-target[0],
            (*it)[1]-target[1],(*it)[2]-target[2])));        
            if(dist<minDist)
            (*itout)=255;        
            else            
            (*itout)=0;
        it++;
        itout++;
    }    return result;
}


There are two points that need special attention in the program:

1. After converting the image to Lab space, the target color also needs to be converted. How to do it A temporary image is created.

2. The norm function is used to determine the distance between two colors. Its operation is norm(v). where v is a dim-dimensional vector. In the program, it is a three-dimensional appropriate amount, which is the result of subtracting two color values.

It is worth thinking about whether Vec3i((*it)[0]-target[0],(*it)[1]-target[1],(*it)[2]- What about replacing target[2]) with Vec3i((*it)-target)? The answer is no, because (*it)-target will automatically restrict the type of the subtraction result during the actual operation.

We can get an example effect after setting the target color and threshold like this:

cdet.SetTargetColor(150,150,150);
cdet.SetMinDistance(50);

The road to growth of OpenCV (3): imitating the magic wand tool in PhotoShop

For more OpenCV growth path (3): imitating the magic wand tool in PhotoShop, please pay attention to the PHP Chinese website for related articles!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Photoshop for creating social media graphics?How do I use Photoshop for creating social media graphics?Mar 18, 2025 pm 01:41 PM

The article details using Photoshop for social media graphics, covering setup, design tools, and optimization techniques. It emphasizes efficiency and quality in graphic creation.

How do I prepare images for web use in Photoshop (file size, resolution, color space)?How do I prepare images for web use in Photoshop (file size, resolution, color space)?Mar 13, 2025 pm 07:28 PM

Article discusses preparing images for web use in Photoshop, focusing on optimizing file size, resolution, and color space. Main issue is balancing image quality with quick loading times.

How do I use Photoshop's Content-Aware Fill and Content-Aware Move tools effectively?How do I use Photoshop's Content-Aware Fill and Content-Aware Move tools effectively?Mar 13, 2025 pm 07:35 PM

Article discusses using Photoshop's Content-Aware Fill and Move tools effectively, offering tips on selecting source areas, avoiding mistakes, and adjusting settings for optimal results.

How do I calibrate my monitor for accurate color in Photoshop?How do I calibrate my monitor for accurate color in Photoshop?Mar 13, 2025 pm 07:31 PM

Article discusses calibrating monitors for accurate color in Photoshop, tools for calibration, effects of improper calibration, and recalibration frequency. Main issue is ensuring color accuracy.

How do I use Photoshop's video editing capabilities?How do I use Photoshop's video editing capabilities?Mar 18, 2025 pm 01:37 PM

The article explains how to use Photoshop for video editing, detailing steps to import, edit, and export videos, and highlighting key features like the Timeline panel, video layers, and effects.

How do I create animated GIFs in Photoshop?How do I create animated GIFs in Photoshop?Mar 18, 2025 pm 01:38 PM

Article discusses creating and optimizing animated GIFs in Photoshop, including adding frames to existing GIFs. Main focus is on balancing quality and file size.

How do I prepare images for web using Photoshop (optimize file size, resolution)?How do I prepare images for web using Photoshop (optimize file size, resolution)?Mar 18, 2025 pm 01:35 PM

Article discusses optimizing images for web using Photoshop, focusing on file size and resolution. Main issue is balancing quality and load times.

How do I prepare images for print using Photoshop (resolution, color profiles)?How do I prepare images for print using Photoshop (resolution, color profiles)?Mar 18, 2025 pm 01:36 PM

The article guides on preparing images for print in Photoshop, focusing on resolution, color profiles, and sharpness. It argues that 300 PPI and CMYK profiles are essential for quality prints.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.