Wednesday, 30 March 2016

Accessing Pixel Value at a Location(x,y)

Let us consider a 3 channel image of BGR color ordering
(The BGR color ordering is the default order returned  by imread)
Here the order of the channel is reverse

(We generally use RGB color model while describing about an image.In BGR the color model is same except the order of the channel is reverse)


We use :
Vec3b imagepixel = image.at(x,y);


/*Reading the pixel value of an image at a particular location*/
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <iostream> 
 
  using namespace std;  
  using namespace cv;  
 
  int main() 
  {  
    Mat image; 
    //Reading the color image 
    image = imread("C:\\Users\\arjun\\Desktop\\image003.png", CV_LOAD_IMAGE_COLOR);  
 
    //If image not found
     if (!image.data)                                                                          
     {  
      cout << "No image data \n";  
      return -1;  
     } 
    
     
     //Reading pixel value at location (i,j)
     Vec3b imagepixel = image.at<Vec3b>(250,500);

     //Displaying the pixel value  
     cout<<"imagepixel(BGR)="<<imagepixel<<"\n" ;  
        
     //Display the original image
     namedWindow("Display Image");               
     imshow("Display Image", image);  
  
     waitKey(0);
     return 0;
   }



Input:


Output:





/*Reading the pixel value of an image at a particular location*/
 
 
#include <opencv2/core/core.hpp>  
#include <opencv2/highgui/highgui.hpp>  
#include <iostream> 
 
  using namespace std;  
  using namespace cv;  
 
int main() 
  {  
    Mat image; 
    //Reading the color image 
    image = imread("C:\\Users\\arjun\\Desktop\\image003.png", CV_LOAD_IMAGE_COLOR);  
 
     //If image not found  
       if (!image.data)                                                             
     {  
      cout << "No image data \n";  
      return -1;  
     } 
 
 
    while(1)
    {
     //Taking inputs from the user for the co-ordinates of the image 
      int i,j;
      cout<<"Enter the co-ordinates of the image where you want to find the pixel value (i,j): \n";
      cout<<"i<"<<image.rows<<"\t"<<"&"<<"\t"<<"j<"<<image.cols<<"\n";
      
     cout<<"i= ";  cin>>i;
     cout<<"j= ";  cin>>j;
     
     if(i < image.rows) 
      { 
        if(j < image.cols)
          {
           //Reading pixel value at location (i,j)
            Vec3b imagepixel = image.at<Vec3b>(i,j); 
           //Displaying the pixel value                                                        
           cout<<"imagepixel(BGR)="<<imagepixel<<"\n" ;
          }  
        }
      else
        { 
           cout<<"Image Co-ordinates value out of range \n"; 
        }
 
     }
        return 0; 
  }


Input:


Output:



No comments:

Post a Comment