http://blog.csdn.net/u010910436/article/details/40399437
首先介紹算法思路:圖像對應方向的投影,就是在該方向取一條直線,統計垂直於該直線(軸)的圖像上的像素的黑點數量,累加求和作為該軸該位置的值;基於圖像投影的切割就是將圖像映射成這種特征后,基於這種特征判定圖像的切割位置(坐標),用這個坐標來切割原圖像,得到目標圖像。
其實,可以用多次的腐蝕后再膨脹進行邊界定位處理,但是如果圖像(比如打印字體)非常規范,簡單的投影就可以了。
java代碼實現:
java的圖像處理,這里大部分是由im.read讀取,bufferedimage,然后轉為二值bitset做處理(0,1或者說是true和false,一個bitset是整張圖片的0,1像素值的一維行向量。bitset.length=width*height)
/**
* 圖像向x軸做投影后的數組
*
* @param imagedata
* @param w
* 寬
* @param h
* 高
* @return
*/
public static int[] xpro(BitSet bitSet, int width, int height) {
int xpro[] = new int[width];
for (intj = 0; j < width; j++) {
for (inti = 0; i < height; i++) {
if (bitSet.get(i *width + j) ==true)
xpro[j]++;
}
}
returnxpro;
}
/**
* 圖像向y軸做投影后的數組
*
* @param imagedata
* @param w
* @param h
* @return
*/
public static int[] ypro(BitSet bitSet, int width, int height) {
int ypro[] = new int[height];
for (inti = 0; i < height; i++) {
for (intj = 0; j < width; j++) {
if (bitSet.get(i *width + j) ==true)
ypro[i]++;
}
}
returnypro;
}
public static Rectangle[] yproSegment(int[] ypro, int width,int height) {
ArrayList<Integer> lline =new ArrayList<Integer>();
ArrayList<Integer> rline =new ArrayList<Integer>();
// 兩種情況:sku區域起始位置元素為空白區域;起始位置含字符元素
if (ypro[0] != 0) {
lline.add(0);
}
for (inti = 4; i < height; i++) {
if (ypro[i] > 0 &&ypro[i - 1] > 0 &&ypro[i - 2] > 0
&& ypro[i - 3] > 0 &&ypro[i - 4] == 0) {
lline.add(i-4);
} else if (ypro[i] == 0 &&ypro[i - 1] > 0 &&ypro[i - 2] > 0
&& ypro[i - 3] > 0 &&ypro[i - 4] > 0) {
rline.add(i);
}
}
if (ypro[ypro.length - 1] != 0) {
rline.add(height);
}
List<Rectangle> c = new ArrayList<Rectangle>();
for (inti = 0; i < rline.size(); i++) {
if (rline.get(i) != 0 &&lline.get(i) <rline.get(i)) {
c.add(new Rectangle(0,lline.get(i),width, rline.get(i)-lline.get(i)));
} else {
break;
}
}
return c.toArray(new Rectangle[0]);
}