我试图构建一个程序,可以从图像中删除单色边框。如何从图像中删除未知宽度的边框
边框始终为白色,但左侧和右侧的边框宽度可能不同于顶部和底部边框的宽度。所以我想要提取的图像集中在源图像中。
所以从下面的图片我想提取绿色的矩形。
此刻,我不知道如何开始解决这个问题。
UPDATE
所以最后calsign的代码段,它的一些改进,解决了我的问题。我意识到内部图像周围的边框可能不是完全单一的颜色,但可以略有不同。这导致一些图像留下一个小边界的行为。
我通过比较两种颜色的颜色距离和阈值来改善两个像素的颜色比较,从而解决了这个问题。当距离低于阈值时,颜色被平等地处理。
public Bitmap cropBorderFromBitmap(Bitmap bmp) {
//Convenience variables
int width = bmp.getWidth();
int height = bmp.getHeight();
int[] pixels = new int[height * width];
//Load the pixel data into the pixels array
bmp.getPixels(pixels, 0, width, 0, 0, width, height);
int length = pixels.length;
int borderColor = pixels[0];
//Locate the start of the border
int borderStart = 0;
for(int i = 0; i < length; i ++) {
// 1. Compare the color of two pixels whether they differ
// 2. Check whether the difference is significant
if(pixels[i] != borderColor && !sameColor(borderColor, pixels[i])) {
Log.i(TAG,"Current Color: " + pixels[i]);
borderStart = i;
break;
}
}
//Locate the end of the border
int borderEnd = 0;
for(int i = length - 1; i >= 0; i --) {
if(pixels[i] != borderColor && !sameColor(borderColor, pixels[i])) {
Log.i(TAG,"Current Color: " + pixels[i]);
borderEnd = length - i;
break;
}
}
//Calculate the margins
int leftMargin = borderStart % width;
int rightMargin = borderEnd % width;
int topMargin = borderStart/width;
int bottomMargin = borderEnd/width;
//Create the new, cropped version of the Bitmap
bmp = Bitmap.createBitmap(bmp, leftMargin, topMargin, width - leftMargin - rightMargin, height - topMargin - bottomMargin);
return bmp;
}
private boolean sameColor(int color1, int color2){
// Split colors into RGB values
long r1 = (color1)&0xFF;
long g1 = (color1 >>8)&0xFF;
long b1 = (color1 >>16)&0xFF;
long r2 = (color2)&0xFF;
long g2 = (color2 >>8)&0xFF;
long b2 = (color2 >>16)&0xFF;
long dist = (r2 - r1) * (r2 - r1) + (g2 - g1) * (g2 - g1) + (b2 - b1) *(b2 - b1);
// Check vs. threshold
return dist < 200;
}
是图像的黑线的一部分? –
不,我只是添加了黑线,以显示图像的整个维度与其边界。 – Flo
嘿!你能上传createBitmap的代码吗? –