OPENCV image Processing

Source: Internet
Author: User

OPENCV implementation of grayscale, two value->canny edge detection and contrast (contrast) and luminance (brightness) value adjustment

Image grayscale: The simple is to make r,g,b value in the threshold [0,255] to obtain the same value, a total of 256 levels, black and white two colors can actually be regarded as the grayscale in the two extremes of the situation, the middle of 254 levels respectively represents the degree of gray (shallow depth).

Image binary: The simple point is to set the gray value of the pixel on the image to (0,0,0) (black) or (255,255,255) (white), so that the image only shows a clear black and white effect.

Canny operator: The aim is to find an optimal edge detection algorithm that satisfies three main criteria:

1. Low error Rate: Identify as many edges as possible while minimizing the impact of noise;

2. High positioning: The identified edges should be as close as possible to the actual edges of the image;

3. Minimum response: The edges in the image can only be identified once, and image noise that may exist should not be identified as edges.

Canny Edge detection step: filter, calculate gradient amplitude and direction, non-maximum value suppression (excluding non-edge pixels, preserving candidate edges) (the specific principle of each step can refer to the OPENCV3 programming primer This book, Baidu a PDF version should be able to find, suggest the best to buy a copy, Make a statement: Definitely not advertising ('? ') )

Brightness and contrast adjustment: first understand the concept of point operations (Point Operators): Calculate the value of the output pixel based on the input pixel value (sometimes with some global information or parameters). Such operators include brightness and contrast adjustment, color correction (colorcorrection), and Transformations (transformations). The two most common point operations are the following:

G (i,j) =a*f (i,j) +b

(A control contrast, b control brightness, F (i,j) is the source image pixel, g (i,j) is the output image pixel)

This demo also uses three for loops to perform an adjustment of the image brightness and contrast. Not much nonsense, the code will not deceive, ('? '). ).

The project code is as follows:

-----------------------------------"header file contains part"-----------------------------------------
Description: Contains the header file that the program depends on
//----------------------------------------------------------------------------------------------
#include <cv.h>
#include #include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

-----------------------------------the Namespace Declarations section--------------------------------------
Description: Contains the namespace used by the program
//---------------------------------------------------------------------------------------------
using namespace Std;
using namespace CV;

-----------------------------------the global variable Declarations section--------------------------------------
Description: Global variable declaration
//---------------------------------------------------------------------------------------------
int g_ncontrastvalue; Value of contrast
int g_nbrightvalue; Luminance value
int thresh = 50;

-----------------------------------the global Function declaration Section--------------------------------------
Description: Global function declaration
//---------------------------------------------------------------------------------------------
static void contrastandbright (int);
void Showhelptext ();

-----------------------------------"Declare image iplimage pointer"----------------------------------
Description: Declaration Image Iplimage Pointer
//---------------------------------------------------------------------------------------------
iplimage* g_psrcimg = NULL;

iplimage* g_pgrayimage = NULL;

iplimage* g_pcannyimg = NULL;

Iplimage *g_pbinaryimage = NULL;

Iplimage *g_pdstimage = NULL;


Sliding Bar response function

void ontrackerslid (int thresh)

{

Cvcanny (G_pgrayimage, g_pcannyimg, (float) thresh, (float) thresh * 3, 3);

Cvshowimage ("Canny Image", g_pcannyimg);

}

-----------------------------the On_trackbar () function------------------------------------
Description: Image binary threshold callback function
//-----------------------------------------------------------------------------------------------
void On_trackbar (int pos)
{
Convert to binary graph
Cvthreshold (G_pgrayimage, G_pbinaryimage, POS, 255, cv_thresh_binary);
Show binary graphs
Cvshowimage ("Binary Image", g_pbinaryimage);
}


-----------------------------------the main () function--------------------------------------------
Description: The entry function for the console application, where the program starts execution
//-----------------------------------------------------------------------------------------------
int main (int argc, char** argv)

{
System ("Color 5F");
Showhelptext ();
if (argc! = 2)

ARGV[1] = "1.jpg";

Set initial values for contrast and brightness

G_ncontrastvalue = 80;
G_nbrightvalue = 80;

Load an image and force it into gray

if ((g_psrcimg = Cvloadimage (argv[1], 1))! = 0)

{

cout << "Press ESC to Quit" << Endl;

Convert color space from RGB to Gray

G_pgrayimage = Cvcreateimage (Cvgetsize (g_psrcimg), 8, 1);

Cvcvtcolor (g_psrcimg, G_pgrayimage, Cv_rgb2gray);

Create a two value graph
G_pbinaryimage = Cvcreateimage (Cvgetsize (g_pgrayimage), ipl_depth_8u, 1);

Canny edge Detection

g_pcannyimg = Cvcreateimage (Cvgetsize (g_pgrayimage), ipl_depth_8u, 1);

Cvnamedwindow ("Contrastandbrightnesswnd", cv_window_autosize);

Create a track bar

Cvcreatetrackbar ("Contrast:", "Contrastandbrightnesswnd", &g_ncontrastvalue, Contrastandbright);
Cvcreatetrackbar ("Brightness:", "Contrastandbrightnesswnd", &g_nbrightvalue, Contrastandbright);


Call callback function
Contrastandbright (G_ncontrastvalue);
Contrastandbright (G_nbrightvalue);

Create window

Cvnamedwindow ("Source Image", cv_window_autosize);

Cvnamedwindow ("Gray Image", cv_window_autosize);

Cvnamedwindow ("Canny Image", cv_window_autosize);

Cvnamedwindow ("Binary Image", cv_window_autosize);

Slide Bar
int nthreshold = 0;
Cvcreatetrackbar ("Threshold:", "Binary Image", &nthreshold, 254, On_trackbar);
On_trackbar (1);

Add a slider to adjust the threshold for edge detection

Ontrackerslid (Thresh);

Cvshowimage ("Gray Image", g_pcannyimg);

Cvcreatetrackbar ("Threshold", "Canny Image", &thresh, Ontrackerslid);

Display image

Cvshowimage ("Source Image", g_psrcimg);

Cvshowimage ("Gray Image", g_pgrayimage);

Save Image

Cvsaveimage ("Gray_image.jpg", g_pgrayimage);

Cvsaveimage ("Canny_image.jpg", g_pcannyimg);

Cvsaveimage ("Binary image.jpg", g_pbinaryimage);


Wait for the "ESC" key to exit

while (1)

if (cvwaitkey (100) = = 27)

Break

Destroying Windows

Cvwaitkey (0);

Cvdestroywindow ("Source Image");

Cvdestroywindow ("Canny Image");

Cvdestroywindow ("Gray Image");

Cvdestroywindow ("Binary Image");

Release image

Cvreleaseimage (&g_pgrayimage);

Cvreleaseimage (&G_PCANNYIMG);

Cvreleaseimage (&G_PSRCIMG);

Cvreleaseimage (&g_pbinaryimage);

return 0;

}

return-1;

}


-----------------------------the Contrastandbright () function------------------------------------
Description: A callback function that alters image contrast and luminance values
//---------------------------------------------------------------------------------------------
static void Contrastandbright (int)
{

   //Three for loop, perform operation dstimg (i,j) = A*srcimg (i,j) + b
    Mat srcimg, dstimg;
    srcimg = Imread ("lena.jpg");
    if (!srcimg.data)
    {
        printf ("Read srcimg picture Error ~! \ n ");
        return;
   }
    dstimg = Mat::zeros (Srcimg.size (), Srcimg.type ());

for (int y = 0; y < srcimg.rows; y++)
{
for (int x = 0; x <srcImg.cols; × x + +)
{
for (int c = 0; c < 3; C + +)
{
Dstimg.at<vec3b> (y, x) [c] = saturate_cast<uchar> ((g_ncontrastvalue*0.01) * (srcimg.at<vec3b> (y, x) [c]) + G_nbrightvalue);
}
}
}

Display image
Imshow ("Contrastandbrightnesswnd", dstimg);
}

-----------------------------------the Showhelptext () function----------------------------------
Description: Output Some help information
//----------------------------------------------------------------------------------------------
void Showhelptext ()
{

printf ("\n\n\t\t\t run Platform for Win32 vs2013\n");
printf ("\n\n\t\t\t opencv a powerful visual library worth your learning \ n");
printf ("\n\n\t\t\t is currently using the OpenCV version:" cv_version);
printf ("\ n \-------------------------------------------------------------------------------------------------- ----------------\ n ");
}

Program Run Results

The author is still a small rookie, if there is a mistake, please point out, communicate with each other, ('? ') ).

OPENCV image Processing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.