I'm trying to access Pixel by Pixel of an IplImage. Im using Java and Processing, and sometimes I need to access pixel by pixel. I've done this so far, but I don't know what's wrong:
public IplImage PImageToIplImage(PImage imageSrc)
{
IplImage imageDst;
if(imageSrc.format==RGB)
{
imageDst = IplImage.create(imageSrc.width, imageSrc.height, IPL_DEPTH_8U, 3);
ByteBuffer imagePixels=imageDst.getByteBuffer();
int locPImage, locIplImage, x, y;
for(y=0; y<imageSrc.height; y++)
for(x=0; x<imageSrc.width; x++)
{
locPImage = x + y * width;
locIplImage=y*imageDst.widthStep()+3*x;
imagePixels.put(locIplImage+2, (byte)(red(imageSrc.pixels[locPImage])));
imagePixels.put(locIplImage+1, (byte)(green(imageSrc.pixels[locPImage])));
imagePixels.put(locIplImage, (byte)(blue(imageSrc.pixels[locPImage])));
}
}
}
After Karlphilip sugestion, I came to this, still doens't work. When I try to show, it gives me a nullPointer exception:
imageDst = IplImage.create(imageSrc.width, imageSrc.height, IPL_DEPTH_8U, 3);
CvMat imagePixels = CvMat.createHeader(imageDst.height(), imageDst.width(), CV_32FC1);
cvGetMat(imageDst, imagePixels, null, 0);
int locPImage, x, y;
for(y=0; y<imageSrc.height; y++)
for(x=0; x<imageSrc.width; x++)
{
locPImage = x + y * width;
CvScalar scalar = new CvScalar();
scalar.setVal(0, red(imageSrc.pixels[locPImage]));
scalar.setVal(1, green(imageSrc.pixels[locPImage]));
scalar.setVal(2, blue(imageSrc.pixels[locPImage]));
cvSet2D(imagePixels, y, x, scalar);
}
imageDst = new IplImage(imagePixels);
The fastest way to iterate over each pixel in JavaCV is:
The following code loads an image from the disk and performs a grayscale conversion by iterating over the pixels of the image:
Not sure if creating a new
CvMat
is the best approach, but it's the only way I know to work in javacv.EDIT:
Unfortunately you use data types that are not from OpenCV,
like PImage
, but I did my best to simulate what you are doing.