对于这样的图片:
抠出其中的黑色区域,效果如下:
import cv2
import numpy as np
import matplotlib.pyplot as plt
import time
def findUnicomArea(img):
#先二值化
ret,threshold = cv2.threshold(img,128,255,cv2.THRESH_BINARY)
img_flag = np.zeros(threshold.shape,np.int8)
count = 0
findpoint = []
#首先遍历图像找到所有的联通区
for x in range(threshold.shape[0]):
for y in range(threshold.shape[1]):
if(threshold[x][y] == 0 and img_flag[x][y] == 0):
#这里表示已经找到了一个没有标志过的黑点,是一个新的联通区
count += 1
img_flag[x][y] = count
findpoint.append((x,y))
while len(findpoint) > 0:
xx,yy = findpoint.pop()
if xx > 0 :#上面
if threshold[xx-1][yy] == 0 and img_flag[xx-1][yy] == 0:
findpoint.append((xx-1,yy))
img_flag[xx-1][yy] = count
if xx < img.shape[0]:#下面
if threshold[xx + 1][yy] == 0 and img_flag[xx + 1][yy] == 0:
findpoint.append((xx + 1, yy))
img_flag[xx+1][yy] = count
if yy > 0:#左面
if threshold[xx][yy-1] == 0 and img_flag[xx][yy-1] == 0:
findpoint.append((xx, yy-1))
img_flag[xx][yy-1] = count
if yy < img.shape[1]:#右面
if threshold[xx][yy+1] == 0 and img_flag[xx][yy+1] == 0:
findpoint.append((xx, yy+1))
img_flag[xx][yy+1] = count
#联通区任然存在一张表中,需要将其分离
coutours = []
for num in range(1,count+1):
coutours.append([])
for x in range(img_flag.shape[0]):
for y in range(img_flag.shape[1]):
if img_flag[x][y] == num:
coutours[num-1].append([x,y,img_flag[x][y]])
desCoutous = np.empty(len(coutours),np.object)
for num in range(len(coutours)):
#将分离后的图像提取出来。计算出联通区所在的范围
tmp = np.mat(coutours[num])
minX = np.min(tmp[:,0])
maxX = np.max(tmp[:,0])
minY = np.min(tmp[:,1])
maxY = np.max(tmp[:,1])
desCoutous[num] = img[minX:maxX,minY:maxY]
return desCoutous
#测试程序如下
img =