计算联通区域

对于这样的图片:
这里写图片描述

抠出其中的黑色区域,效果如下:
这里写图片描述

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 =
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值