Wednesday, December 10, 2014

Image processing Practicals - Part 2 (Getting pixel information of an image using opencv)


This is the second post in this post series. Before read this, please refer to my first post  if you haven't configured opencv in your pc .

Before do any image processing task it is important to identify how an image has been constructed. Basically a raster image is a collection of pixels(A matrix of pixels). One pixel has three channels. Those are called as Red,Green and Blue. By using opencv we can see how an image has been constructed. Normally each channel is represented by 8 bits. So all together its 24 bits(3 Bytes).

Let's run this code and see the output in the console. Program 1 uses a for loop to go through pixels. But if you only need to see pixels(Not to analyse) just use cout function for display the pixel information(See program 2).

Program 1


1:  #include <opencv2/core/core.hpp>  
2:  #include <opencv2/highgui/highgui.hpp>  
3:  #include <iostream>  
4:  using namespace std;  
5:  using namespace cv;  
6:  int main() {  
7:   Mat image;  
8:   //Reading the image  
9:   image = imread("lena.jpg", 1);  
10:   //If image not found  
11:   if (!image.data) {  
12:   cout << "No image data \n";  
13:   return -1;  
14:   }  
15:   //Display image  
16:   namedWindow("Display Image");  
17:   imshow("Display Image", image);  
18:   //Print pixel values  
19:   for (int i = 0; i < image.rows; i++) { //take row by row  
20:   for (int j = 0; j < image.cols; j++) { //take each and every pixel in current row  
21:    Vec3b pixel = image.at<Vec3b>(i, j);  
22:    cout << pixel;  
23:   }  
24:   cout << endl;  
25:   }  
26:   waitKey(0);  
27:   return 0;  
28:  }  



Sample output: 


So here we have B,G,R values printed.

Ex; [65,32,93] ----> Blue value = 65, Green value = 32, Red value = 93 of first pixel


Program 2

1:  #include <opencv2/core/core.hpp>  
2:  #include <opencv2/highgui/highgui.hpp>  
3:  #include <iostream>  
4:  using namespace std;  
5:  using namespace cv;  
6:  int main() {  
7:       Mat image;  
8:       //Reading the image  
9:       image = imread("lena.jpg", 1);  
10:       //If image not found  
11:       if (!image.data) {  
12:            cout << "No image data \n";  
13:            return -1;  
14:       }  
15:       //Display image  
16:       namedWindow("Display Image");  
17:       imshow("Display Image", image);  
18:       cout<<image;  
19:       waitKey(0);  
20:       return 0;  
21:  }  

This program is just using a cout function, without using a for loop to go through pixels.

Sample output:




Compare the first program output and second program output. We can see that the second program does not have separated three channels(BGR). So in the second program, first pixel is correspond to first three values.



0 comments:

Post a Comment