Summary and time measurement of opencv2.4+ traversal read-write pixel method

Source: Internet
Author: User

The following text and code is based on the how to scan images of OpenCV 2.4.13.0 documentation , lookup tables and time measurement with OpenCV section, English Good students can read the original text directly.

    • 1. Color compression

Color Reduction The simplest understanding is to reduce the number of colors that represent an image, and we all know that a 8-bit deep 3-channel RGB True color image includes more than 16 million (16777216) of the number of colors, In fact, in some applications there are not so many colors (such as transmission (transmission), split (segmentation), compression (compression)). This is also a small research direction, want to learn more, can read article Adaptive Color reduction,color Reduction and estimation of the number of dominant colors by using A self-growing and self-organized neural gas.

Here, we implement a very simple method:

I_old is the input pixel value, i_new is the output pixel value, dividewidth represents to reduce the degree, we can understand that when the dividewidth is 128, for the grayscale image is to do a threshold value of 128 two value.

A bit more intuitive, the left is a grayscale original image, the right is the output image:

When Dividewidth is 128:

When Dividewidth is 64 o'clock:

According to the above description, in fact this formula we can create a mapping table to avoid repeated calculations, for 0-255 of the limited input values, the establishment of the output value of the mapping table:

Color space divide widthconst int dividewidth = 128;//converting table for reducing color Spaceuchar table[256];//fir St, we should build the converting tablefor (int i = 0; i < i++) {Table[i] = (UCHAR) (Dividewidth * (i/dividewidth ));}

  

Our testing program is doing the following:

1. Read in a grayscale image and an RGB color image;

2. Implement the algorithm according to the four kinds of access pixels described below;

3. Run the algorithm several times, take the average, compare the way of four kinds of access pixels.

    • 2. Storage of image data

First, it outlines how the data is stored in memory . Mat is the basic image type above the opencv2.x version , Mat can be regarded as a matrix, the size of the matrix depends on what color space the mat is, such as the most basic grayscale (gray scale) or RGB,CMYK,YCBCR, etc. , because this determines how many channels the mat has, in general, the grayscale image has only one channel, and the RGB image has three channels.

For grayscale images, the image data is stored in memory:

For multi-channel images, there are several channels, and each column contains many columns. For frequently used RGB-based color spaces, the image data is stored as follows:

It is important to note that the order of the channels is BGR rather than RGB.

In general, each row of the image data is stored continuously in memory because it is more efficient to traverse the image data. MAT provides the iscontinuous () function to get data that is continuously stored.

    • 3. Measurement of Time

OPENCV provides two simple functions, GetTickCount () and gettickfrequency (). GetTickCount returns the number of ticks that have been initiated from the operating system to the current period, and the type is int64. Gettickfrequency returns the number of ticks per second, with a type of double. Therefore, you can use the following code to calculate the time spent in two operations in seconds:

Double dtime = (double) getTickCount ();//Do somethingdtime = ((double) GetTickCount ()-Dtime)/gettickfrequency ();
    • 4. How image pixels are accessed
4.1 PTR operations and pointers-efficient way

This approach is based on the [] operation of. PTR and C, which is also the recommended way to traverse an image.

/** @Method 1:the Efficient Method accept grayscale image and RGB image */int Scanimageefficiet (Mat & image) {//Chann Els of the Imageint ichannels = Image.channels ();//rows (height) of the Imageint irows = image.rows;//cols (width) of the Imageint icols = image.cols * ichannels;//Check if the image data is stored Continuousif (image.iscontinuous ()) {Icols *= Irows;irows = 1;} uchar* p;for (int i = 0; i < irows; i++) {//Get the pointer to the ith ROWP = image.ptr<uchar> (i);//operates on Each pixelfor (int j = 0; J < Icols; J + +) {//assigns new valuep[j] = Table[p[j]];}} return 0;}

This gets a pointer to each row, and then iterates through all the data in that row. When the image data is stored continuously, you only need to take the pointer once, and then you can traverse the entire image data.

4.2 iterators-a more secure way

You need to calculate the amount of data that needs to be traversed compared to an efficient way, and you need to skip some gaps when the data is not contiguous between the rows and rows of the image. The iterator (iterator) approach provides a more secure way to access image pixels. All you have to do is declare two matiterator_ variables, one pointing to the image beginning, one pointing to the end of the image, and then iterating.

/** @Method 2:the iterator (SAFE) Method accept grayscale image and RGB image */int Scanimageiterator (Mat & image) {// Channels of the Imageint ichannels = image.channels (); switch (ichannels) {case 1:{matiterator_<uchar> it, end;for (i t = image.begin<uchar> (), end = Image.end<uchar> (); It! = end; it++) {*it = Table[*it];} break;}  Case 3:{matiterator_<vec3b> it, end;for (it = image.begin<vec3b> (), end = Image.end<vec3b> (); it! = end; it++) {(*it) [0] = table[(*it) [0]];(*it) [1] = table[(*it) [1]];(*it) [2] = table[(*it) [2]];} Break;}} return 0;}

In the case of color images, OPENCV provides a vec3b data type to store because it is a vector of three channels.

    • 4.3 Dynamic address calculation-more suitable for random access

This approach is not recommended for traversing images, and is generally used to randomly access a small amount of image data. The basic usage is to specify the row number and return the pixel value for that position. But you need to know beforehand whether the type of data returned is UCHAR or vec3b or something else.

/** @Method 3:random Access Method accept grayscale image and RGB image */int scanimagerandomaccess (Mat & image) {//C Hannels of the Imageint ichannels = Image.channels ();//rows (height) of the Imageint irows = image.rows;//cols (width) of The Imageint icols = Image.cols;switch (ichannels) {//grayscalecase 1:{for (int i = 0; i < irows; i++) {for (int j = 0; J < Icols; J + +) {image.at<uchar> (i, j) = Table[image.at<uchar> (i, J)];}} break;} Rgbcase 3:{mat_<vec3b> _image = image;for (int i = 0; i < irows; i++) {for (int j = 0; J < Icols; J + +) {_imag E (i, J) [0] = Table[_image (i, J) [0]];_image (I, J) [1] = Table[_image (i, J) [1]];_image (I, J) [2] = Table[_image (i, J) [2]];}} Image = _image;break;}} return 0;}
4.4 Find a table-a way of rowing

OpenCV probably also takes into account that there are many occasions when a single pixel value needs to be changed (such as a luminance transform based on a single pixel value, gamma correction, etc.), so the core module provides a more efficient and one-rowing lut () function for this operation and does not need to traverse the entire image.

First build a mapping lookup table:

Build a Mat type of the lookup Tablemat lookuptable (1, 2, cv_8u); uchar* p = lookuptable.data;for (int i = 0; i < 56; i++) {P[i] = table[i];}

Then call the Lut () function:

Call the Functionlut (image, LookupTable, matout);

Image is the input, matout is the output image.

    • 5. Performance metrics in different ways

Test environment: OPENCV version 3.1.0,windows 7 64-bit system.

The test image is a Lena color map of the 512*512 Lena Grayscale and 512*512. Run 100 different methods separately, and then get the average time as follows:

You can see that the LUT algorithm is slightly better than the efficient method, but both are efficient, and the iterator approach and random access are slow.

Summary and time measurement of opencv2.4+ traversal read-write pixel method

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.