Skip to content

Instantly share code, notes, and snippets.

@simonhaenisch
Last active February 26, 2021 12:11
Show Gist options
  • Save simonhaenisch/62e0ac955f229753c0289bc4b2a8db11 to your computer and use it in GitHub Desktop.
Save simonhaenisch/62e0ac955f229753c0289bc4b2a8db11 to your computer and use it in GitHub Desktop.
Access pixel in an OpenCV Matrix using the data pointer and indexing
// example matrix
Mat img = Mat::zeros(256, 128, CV_32FC3);
// get the pointer (cast to data type of Mat)
float *pImgData = (float *)img.data;
// loop through rows, columns and channels
for (int row = 0; row < img.rows; ++row)
{
for (int column = 0; column < img.cols; ++column)
{
for (int channel = 0; channel < img.channels(); ++channel)
{
float value = pImgData[img.channels() * (img.cols * row + column) + channel];
}
}
}
@kupferb
Copy link

kupferb commented Dec 4, 2019

Thank you for that!.
You should change
float value = pImgData[img.channels() * (img.cols * row + col) + channel];
to
float value = pImgData[img.channels() * (img.cols * row + column) + channel];

@simonhaenisch
Copy link
Author

@kupferb thanks, I updated this (: haven't actually used this since writing my master thesis 3 years ago 🤓

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment