我正在使用opencv通过opencv将android位图转换为grescale。下面是我使用的代码,
IplImage image = IplImage.create( bm.getWidth(), bm.getHeight(), IPL_DEPTH_8U, 4); //creates default image
bm.copyPixelsToBuffer(image.getByteBuffer());
int w=image.width();
int h=image.height();
IplImage grey=cvCreateImage(cvSize(w,h),image.depth(),1);
cvCvtColor(image,grey,CV_RGB2GRAY);
黑石为源镜像。这段代码运行良好,并转换为灰度,我已经通过保存到sdcard然后再次加载进行了测试,但当我尝试使用下面的方法加载它时,我的应用程序崩溃了,任何建议。
bm.copyPixelsFromBuffer(grey.getByteBuffer());
iv1.setImageBitmap(bm);
iv1是我要设置黑石的镜像视图。
发布于 2012-01-15 02:02:40
我从来没有使用过Android的OpenCV绑定,但这里有一些代码可以帮助您入门。就当它是伪代码吧,因为我不能尝试……但是你会得到基本的概念。这可能不是最快的解决方案。我从this answer粘贴过来的。
public static Bitmap IplImageToBitmap(IplImage src) {
int width = src.width;
int height = src.height;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for(int r=0;r<height;r++) {
for(int c=0;c<width;c++) {
int gray = (int) Math.floor(cvGet2D(src,r,c).getVal(0));
bitmap.setPixel(c, r, Color.argb(255, gray, gray, gray));
}
}
return bitmap;
}
发布于 2013-10-30 16:31:55
您的IplImage grey
只有一个频道,而您的Bitmap bm
有4个或3个频道(ARGB_8888
、ARGB_4444
、RGB_565
)。因此,bm
不能存储灰度图像。在使用之前,您必须将其转换为rgba。
示例:(您的代码)
IplImage image = IplImage.create( bm.getWidth(), bm.getHeight(), IPL_DEPTH_8U, 4);
bm.copyPixelsToBuffer(image.getByteBuffer());
int w=image.width(); int h=image.height();
IplImage grey=cvCreateImage(cvSize(w,h),image.depth(),1);
cvCvtColor(image,grey,CV_RGB2GRAY);
如果你想加载它:(你可以重用你的image
或者创建另一个(temp
))
IplImage temp = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 4); // 4 channel
cvCvtColor(grey, temp , CV_GRAY2RGBA); //color conversion
bm.copyPixelsFromBuffer(temp.getByteBuffer()); //now should work
iv1.setImageBitmap(bm);
我想这可能会有帮助!
https://stackoverflow.com/questions/7527917
复制相似问题