How to access elements of single channel IplImage in Opencv
Pixels are stored inside the imageData array. So, since your image is the only channel, you just need to do the following:
myimage.imageData[y*myimage.width+x] = 100;
This provides the correct offset from the beginning of the buffer in imageData and is more readable than any other pointer algebra operation.
In the images of N-channels, it is enough to multiply the array offset by N and add the number of channels for reading:
i.e. for RGB image
myimage.imageData[3*(y*myimage.width+x)+0] = 100; //Red myimage.imageData[3*(y*myimage.width+x)+1] = 100; //Green myimage.imageData[3*(y*myimage.width+x)+2] = 100; //Blue
Any optimization to avoid multiplying the data to get the index can be done according to the goal you need to achieve.
source to share