python寻找图像中的最大连通域

今天在写数字图像处理大作业,要用到仅保留灰度图像中最大的白色区域,于是写了一下保留最大连通域的代码如下:
(没写注释,不懂就问hhh,算法采用的利用栈的朴素算法,1000×1000的图像速度还行,一般般,谁要用的话去main函数里面改一下输入的图像就好了,
只要改:arr改成你的灰度图(只能区分0和大于0);rows和cols的维度设置成arr的维度;然后record的维度和arr一样)

import numpy as np
import cv2
import random

tempLst=[]
size=0
lst=[]
def inLst(i,j):
    for temp in lst:
        if temp[0]==i and temp[1]==j:
            return True
    return False
def filltempLst(i,j,rows,cols,image,record):
    lst1=[[i,j]]
    myRecord=np.zeros(image.shape)
    while len(lst1)>0:
        temp_len=len(lst1)
        temp_i=lst1[temp_len-1][0]
        temp_j=lst1[temp_len-1][1]
        lst1.pop()
        #如果已经涉足其他连通域
        if record[temp_i,temp_j]==1:
            tempLst.clear()
            return False
        tempLst.append([temp_i,temp_j])
        myRecord[temp_i,temp_j]=1
        #看一下四周的元素
        get_i=temp_i-1
        get_j=temp_j
        if get_i>=0 and image[get_i,get_j]>0:
            if myRecord[get_i,get_j]==0:
                myRecord[get_i,get_j]=1
                lst1.append([get_i,get_j])
        get_i=temp_i+1
        get_j=temp_j
        if get_i<rows and image[get_i,get_j]>0:#看一下是否已经在tempLst中
            if myRecord[get_i,get_j]==0:
                myRecord[get_i,get_j]=1
                lst1.append([get_i,get_j])
        get_i=temp_i
        get_j=temp_j-1
        if get_j>=0 and image[get_i,get_j]>0:#看一下是否已经在tempLst中
            if myRecord[get_i,get_j]==0:
                myRecord[get_i,get_j]=1
                lst1.append([get_i,get_j])
        get_i=temp_i
        get_j=temp_j+1
        if get_j<cols and image[get_i,get_j]>0:#看一下是否已经在tempLst中
            if myRecord[get_i,get_j]==0:
                myRecord[get_i,get_j]=1
                lst1.append([get_i,get_j])
    for x in tempLst:
        record[x[0],x[1]]=1
    return True

def getMaxConnect(image,record):
    global size
    global lst
    [rows,cols]=image.shape
    for i in range(rows):
        for j in range(cols):
            if image[i,j]>0:
                if filltempLst(i,j,rows,cols,image,record):
                    if len(tempLst)>size:
                        size=len(tempLst)
                        lst=tempLst[:]
                tempLst.clear()
rows=1000
cols=1000
record=np.zeros((rows,cols))
arr=np.zeros((rows,cols))
for i in range(rows):
    for j in range(cols):
        get=random.random()
        if get>0.5:
            arr[i,j]=255
getMaxConnect(arr,record)
print(size)
print(lst)
cv2.imshow("随机生成的图",arr)
arr=np.zeros(arr.shape)
for x in lst:
    arr[x[0],x[1]]=255
cv2.imshow("前面那个图的最大连通域",arr)
cv2.waitKey(0)

版权声明:本文为turn_my_back原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。