gpt4 book ai didi

android - 如何使用一个像素的 Sobel 矩阵

转载 作者:行者123 更新时间:2023-11-29 17:37:08 29 4
gpt4 key购买 nike

我想在我的 android 应用程序中使用 Sobel 运算符。但是我不明白如何使用一个像素。

int sobel_x[][] = {{-1, 0, 1},
{-2, 0, 2},
{-1, 0, 1}};
int sobel_y[][] = {{-1, -2, -1},
{0, 0, 0},
{1, 2, 1}};
Bitmap source = ImageHelper.GetBitmapGromUri(Path);
int w = source.getWidth();
int h = source.getHeight();
int[] pixels;
pixels = new int[h * w];
source.getPixels(pixels, 0, w, 1, 1, w - 1, h - 1);
for(int i = 0;i < pixels.length;i++){
...
}

我尝试使用 get/setPixel。但是非常非常慢。

最佳答案

好消息和坏消息。以下工作但是......

Android,出于某种特殊原因,不允许您创建 8 位灰度图像。这意味着您必须创建 ARGB_8888 格式的灰度。这可能是您之前版本中的问题所在,我们以字节形式读取数据,而实际情况并非如此。

下面的代码有效,我只在模拟器上针对您的图像运行它,它的速度可笑慢(11 秒)。当然,您的图像非常大,但我猜这仍然是减慢速度的方式。

我强烈建议考虑使用 OpenCV Java 库,因为与 Android 位图类不同,它们速度快且内存效率高!

public class Sobel {
private static Bitmap toGreyScale( Bitmap source ) {
Bitmap greyScaleBitmap = Bitmap.createBitmap(
source.getWidth(), source.getHeight(),
Bitmap.Config.ARGB_8888);

Canvas c = new Canvas(greyScaleBitmap);
Paint p = new Paint();
ColorMatrix cm = new ColorMatrix();

cm.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(cm);
p.setColorFilter(filter);
c.drawBitmap(source, 0, 0, p);
return greyScaleBitmap;
}

public static void doSobel( Bitmap source) {

Bitmap grey = toGreyScale(source);

int w = grey.getWidth();
int h = grey.getHeight();
// Allocate 4 times as much data as is necessary because Android.
int sz = w * h;

IntBuffer buffer = IntBuffer.allocate( sz );
grey.copyPixelsToBuffer( buffer );
final int[] bitmapData = buffer.array();

int[] output = new int[ w * h ];
for( int y=1; y<h-1; y++ ) {
for( int x=1; x<w-1; x++ ) {
int idx = (y * w + x );

// Apply Sobel filter
int tl = (bitmapData[idx - w - 1]) & 0xFF;
int tr = (bitmapData[idx - w + 1]) & 0xFF;
int l = (bitmapData[idx - 1]) & 0xFF;
int r = (bitmapData[idx + 1]) & 0xFF;
int bl = (bitmapData[idx + w - 1]) & 0xFF;
int br = (bitmapData[idx + w + 1]) & 0xFF;

int sx = (int) ( tr - tl + 2 * ( r - l ) + br - bl );
sx = sx & 0xFF;

// Put back into ARG and B bytes
output[toIdx] = (sx << 24) | ( sx << 16) | (sx << 8) | sx;
}
}

source.copyPixelsFromBuffer( IntBuffer.wrap(output));
}
}

关于android - 如何使用一个像素的 Sobel 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30107271/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com