我正在尝试逐个像素地访问 IplImage 的像素。我使用 Java 和处理,有时我需要逐像素访问。到目前为止我已经这样做了,但我不知道出了什么问题:
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])));
}
}
}
在Karlphilip sugestion 之后,我来到这里,仍然无法正常工作。当我尝试显示时,它给了我一个 nullPointer 异常:
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);