Table of Contents
1. Several common color spaces:
2. Color space conversion in OpenCV
3. Simple magic wand program
Home Web Front-end PS Tutorial The road to growth of OpenCV (3): imitating the magic wand tool in PhotoShop

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

Feb 20, 2017 am 09:09 AM
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};
Copy after login

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;
}
Copy after login


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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
Advanced Photoshop Tutorial: Master Retouching & Compositing Advanced Photoshop Tutorial: Master Retouching & Compositing Apr 17, 2025 am 12:10 AM

Photoshop's advanced photo editing and synthesis technologies include: 1. Use layers, masks and adjustment layers for basic operations; 2. Use image pixel values ​​to achieve photo editing effects; 3. Use multiple layers and masks for complex synthesis; 4. Use "liquefaction" tools to adjust facial features; 5. Use "frequency separation" technology to perform delicate photo editing, these technologies can improve image processing level and achieve professional-level effects.

Photoshop's Key Features: A Deep Dive Photoshop's Key Features: A Deep Dive Apr 19, 2025 am 12:08 AM

Key features of Photoshop include layers and masks, adjustment tools, filters and effects. 1. Layers and masks allow independent editing of image parts. 2. Adjust tools such as brightness/contrast can modify image tone and brightness. 3. Filters and effects can quickly add visual effects. Mastering these features can help creative professionals achieve their creative vision.

Using Photoshop: Creative Possibilities and Practical Uses Using Photoshop: Creative Possibilities and Practical Uses Apr 22, 2025 am 12:09 AM

Photoshop is very practical and creative in practical applications. 1) It provides basic editing, repairing and synthesis functions, suitable for beginners and professionals. 2) Advanced features such as content recognition fill and layer style can improve image effects. 3) Mastering shortcut keys and optimizing layer structure can improve work efficiency.

Photoshop and Digital Art: Painting, Illustration, and Compositing Photoshop and Digital Art: Painting, Illustration, and Compositing Apr 18, 2025 am 12:01 AM

Photoshop's applications in digital art include painting, illustration and image synthesis. 1) Painting: Using brushes, pencils and mixing tools, the artist can create realistic effects. 2) Illustration: With vector and shape tools, artists can accurately draw complex graphics and add effects. 3) Synthesis: Using mask and layer blending mode, artists can seamlessly blend different image elements.

Using Photoshop for Graphic Design: Branding and More Using Photoshop for Graphic Design: Branding and More Apr 16, 2025 am 12:02 AM

The steps to using Photoshop for brand design include: 1. Use the Pen tool to draw basic shapes, 2. Add shadows and highlights through layer styles, 3. Adjust colors and details, 4. Use smart objects and actions to automatically generate different versions of the design. Photoshop helps designers create and optimize brand elements with the flexibility of layers and masks, ensuring consistency and professionalism of designs, from simple logos to complex branding guides.

Photoshop for Photographers: Enhancing and Retouching Images Photoshop for Photographers: Enhancing and Retouching Images Apr 25, 2025 am 12:01 AM

Enhance and retouching photos in Photoshop can be achieved by adjusting brightness and contrast, using the Repair Brush Tool. 1) Adjust brightness and contrast: Increase brightness and contrast to improve underexposed photos through the Image->Adjustments->Brightness/Contrast menu. 2) Use the Repair Brush Tool: Select HealingBrushTool in the toolbar and apply to remove miscellaneous points or scars in the image.

What Photoshop Does Best: Common Tasks and Projects What Photoshop Does Best: Common Tasks and Projects Apr 23, 2025 am 12:06 AM

Photoshop is specialized in image editing, layering and masking, digital painting and a variety of design applications. 1) Image editing and repair: remove defects and adjust color and brightness. 2) Layers and masks: non-destructive editing and creation. 3) Digital paintings and illustrations: create art works. 4) Practical applications: graphic design, web design and digital art creation.

Photoshop: A Versatile Tool for Image Manipulation Photoshop: A Versatile Tool for Image Manipulation Apr 27, 2025 am 12:13 AM

Photoshop is so powerful in the field of image processing because of its versatility and intuitive operating interface. 1) It can handle various tasks from basic adjustment to complex synthesis, such as adjusting brightness and contrast. 2) Working based on layers and masks allows non-destructive editing. 3) Examples of usage include adjusting color balance and creating layer masks. 4) Common errors such as excessive editing can be avoided through the History panel. 5) Performance optimization suggestions include the use of smart objects and shortcut keys.

See all articles