"OPENCV Study notes" I. Manipulating pixels

Source: Internet
Author: User

Recently opened a new hole for oneself, intends to study the next OPENCV this computer vision library.

Reference: "OpenCV 2 computer Vision Programming Handbook"

"The following default version OpenCV 2.3.1"

The simplest thing to do is to traverse a pixel on a picture, however, there are many ways to traverse it, and the choice is key.

A brief introduction to several common ways:

1. Pointer traversal:

int row = Image.rows;int col = image.cols * Image.channels (); for (int i = 0; i < row; i++) {    uchar* data = image.ptr <uchar> (i);    for (int j = 0; J < Col; J + +) {        ...    }}

The principle is simple and easy to understand, like traversing a two-dimensional matrix. First get the number of rows and columns (number of pixel columns * channels), such as black and white picture channel number is 1, color picture of the number of channels is 3. Each line then points to the first address of the row. One point to note is that each time you need to get the first address of the line, because in the efficiency of consideration, the end of each line of the address of the next element of the address is not equal to the address of the first element of the next line, but will add some extra pixels. The reason for this is that some multimedia processing chips can process images more efficiently.

Based on this feature, we can get the following improved version:

int row = Image.rows;int col = image.cols * Image.channels (), if (Image.iscontinuous ()) {//judgment there are no extra supplemental pixels    col = col * row;    row = 1;} for (int i = 0; i < row; i++) {    uchar* data = image.ptr<uchar> (i);    for (int j = 0; J < Col; J + +) {        ...    }}

As the code shows, for images that do not have additional pixels, the call to PTR can be greatly reduced, which is extremely desirable in cases where multiple small images are handled.

2. Iterator Traversal:

Iterators provide a relatively common and universal way of using methods that hide internal implementations. Greatly improves the readability of the code.

Cv::mat_<cv::vec3b>::iterator it = image.begin<cv::vec3b> (); Cv::mat_<cv::vec3b>::iterator itend = Image.end<cv::vec3b> (); for (; it! = Itend; ++it) {    ...}
In the process of traversal, because of the color image processing, we can access by operator [], such as (*it) [0] and(*it) [2].


Thus, after the get traversal skill, we can simply implement some of the basics of slice sharpening. The following is a list of my console-based code, and a simple example of an effect diagram.




#include <opencv2\opencv.hpp> #include <iostream> #include <string> #include <stdio.h>using Namespace Std;using namespace cv;/*-------------------Add salt and pepper noise---------------------*/void Salt (const Cv::mat &    Input, Cv::mat &output, int n) {input.copyto (output);    int col = Output.cols;    int row = Output.rows;int channel = Output.channels ();        for (int i = 0; i < n; i++) {int x = rand ()% row;        int y = rand ()% Col;        if (channel = = 1) {output.at<uchar> (x, y) = 0;            } else {output.at<cv::vec3b> (x, y) [0] = 0;            Output.at<cv::vec3b> (x, y) [1] = 0;        Output.at<cv::vec3b> (x, y) [2] = 0; }}}/*-------------------Color reduction function---------------------*/void colorreduce (const Cv::mat &input, Cv::mat &output , int div = *) {if (input.iscontinuous ()) {Input.reshape (1, Input.cols * input.rows);}    int row = Input.rows;    int NC = Input.cols * Input.channels (); for (int i = 0; i < row;        i++) {Const uchar* data_in = input.ptr<uchar> (i); uchar* data_out = output.ptr<uchar> (i);        for (int j = 0; J < NC; J + +) {Data_out[j] = data_in[j]/div * div + div/2; }}}/*-------------------Color reduction function---------------------*/void sharpen2d (const Cv::mat &input, Cv::mat &output) { Construct the kernel (and initialize the other items to 0) Cv::mat kernel (3, 3, cv_32f, Cv::scalar (0));//Assign a value to the kernel element kernel.at<float> (0, 1) = -1.0;kernel.at <float> (1, 0) = -1.0;kernel.at<float> (1, 2) = -1.0;kernel.at<float> (2, 1) = -1.0;kernel.at<float > (1, 1) = 5.0;//Filter the image cv::filter2d (input, output, input.depth (), kernel);} /*-------------------Add watermark function---------------------*/void getwatermark (Cv::mat &logo, Cv::mat &output) {// Define image roicv::mat Imageroi;int row = output.rows, col = output.cols;int Logo_row = logo.rows, Logo_col = logo.cols;if (Row &lt ; Logo_row | | Col < Logo_col) {puts ("The logo is too large or the picture is too small, the watermark failed to load"); return; Imageroi = output (Cv::rect (Col-logo_col, Row-logo_row, Logo_col, Logo_row));//load Mask and insert Logologo.copyto (imageroi, logo);}    /*--------------------main function----------------------*/int main () {std::string str;cv::mat output;    Puts ("Enter the image name, including the file suffix part:");    CIN >> str;        Cv::mat input = Cv::imread (str), if (Input.empty ()) {cout<< "error" << Endl;    return-1; }cout << "The picture was opened successfully, the size of the picture is:"; cout << input.size (). Width << "*" << input.size (). Height << "Pixels." << endl;int type;int vis[10] = {0};cout << "1. Show original image" << endl;cout << "2. Add salt and pepper noise" << end L;cout << "3. Color reduction" << endl;cout << "4. Image Sharpening" << endl;cout << "5. Add logo" << endl;cout &L t;< "6. Show current modified image" << endl;cout << "0. Exit << Endl;while (True) {cout <<" Enter the action number you want (press ENTER to end): "<< endl;cin >> type;if (Type < 0 | | Type > 6) {cout << "invalid action" << endl;continue;} if (Vis[type]) {cout << "The operation has been performed, please try other features"<< Endl;}  else Vis[type] = 1;if (type = = 1) {cv::imshow ("original image", input), Cv::waitkey ();} else if (type = = 2) {Salt (input, output, 3000);} else if (type = = 3) {colorreduce (input, Output),} else if (type = = 4) {sharpen2d (input, output);} else if (type = = 5) {bool exist = false;for (int i = 1; I <= 6; i++) {if (i = = 5) continue;else if (vis[i]) exist = true;} if (!exist) {cout << "current output picture does not exist" << endl;vis[type] = false;continue;} Cv::mat logo = Cv::imread ("Gx_logo.png"); Getwatermark (logo, output);} else if (type = = 6) {Cv::namedwindow ("dog"); Cv::imshow ("dog", Output); Cv::waitkey ();} else if (type = = 0) {break;}}    Cv::imwrite ("haha.bmp", Output);p UTS ("End of Operation");    System ("pause"); return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"OPENCV Study notes" I. Manipulating pixels

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.