Search code examples
imageopencvpixel

How can I access each pixel in OpenCV, perform an operation and return the new information to the image?


I am trying to access each pixel of the image to perform an operation and return it back to the image, someone has some idea of ​​how to do it since I have done this but it marks me wrong when compiling.

 #include <opencv2/opencv.hpp>
 #include <opencv2/highgui/highgui.hpp> 
 #include <stdio.h>

 using namespace cv;
 using namespace std;
 int main( int argc, char** argv ){

    char* source_window = "Source image";
    Mat nueva;
    Mat img = imread("img.jpg",CV_LOAD_IMAGE_COLOR);
    unsigned char *input = (unsigned char*)(img.data);

    int i,j,b;
    for(int i = 0;i < img.cols;i++){
        for(int j = 0;j < img.rows;j++){
           b = input[i+1][j+1] ;
           nueva[i][j] = b;
         }
     }

     imshow( source_window, nueva );

 }

Solution

  • I think that this code you could use

     int nl= image.rows; 
     int nc= image.cols * image.channels();
     for (int j=0; j<nl; j++) {
        uchar* data= image.ptr<uchar>(j);
        for (int i=0; i<nc; i++) {
           data[i]= data[i]/div*div + div/2;
        }
     }