使用鼠标交互实现区域生长算法

部署运行你感兴趣的模型镜像

案例© Fu Xianjun. All Rights Reserved. 

一:导包

import cv2 
import numpy as np

二:定义Point类
class Point(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def getX(self):
        return self.x
    def getY(self):
        return self.y

三:计算像素偏差
def getGrayDiff(img,currentPoint,tmpPoint):
    return abs(int(img[currentPoint.x,currentPoint.y]) -int(img[tmpPoint.x,tmpPoint.y]))

四:设置八领域

def selectConnects(p):
    if p==8:
        connects = [Point(-1, -1), Point(0, -1), Point(1, -1), Point(1, 0), Point(1, 1),Point(0, 1), Point(-1, 1), Point(-1, 0)]
    else:
        connects = [Point(0, -1), Point(1, 0),Point(0, 1),Point(-1, 0)]
    return connects

五:定义生长函数

def regionGrow(img,seeds,thresh,p = 4):
    height, weight = img.shape
    seedMark = np.zeros(img.shape)    #生成和原图相同大小的seedMark

    seedList = []
    for seed in seeds:
        seedList.append(seed)
        label = 1
    connects = selectConnects(p)  #选择领域
    while(len(seedList)>0):
        currentPoint = seedList.pop(0)  #弹出第一个元素
        seedMark[currentPoint.x,currentPoint.y] = label  #将第一个seedMark赋值label 

        #以种子点位中心进行比较
        for i in range(p):
            tmpX = currentPoint.x + connects[i].x
            tmpY = currentPoint.y + connects[i].y

            #判断是点是否在图像内
            if tmpX < 0 or tmpY < 0 or tmpX >= height or tmpY >= weight:
                continue

            grayDiff = getGrayDiff(img,currentPoint,Point(tmpX,tmpY))   #判断邻域点和种子点的差值

            #如果差值小于阈值且位被分类,则赋值label,作为下一个种子点放入seedList

            if grayDiff < thresh and seedMark[tmpX,tmpY] == 0:
                seedMark[tmpX,tmpY] = label
                seedList.append(Point(tmpX,tmpY))
    return seedMark

六:鼠标交互

def mouse(event,x,y,flages,param):
    if event==cv2.EVENT_LBUTTONDOWN:
        seeds=[Point(x,y)]
        binaryImg=regionGrow(img,seeds,3)
        cv2.imshow("binaryImg",binaryImg)

七:应用区域生长

img=cv2.imread("peppa.jpg",0)  #导图
cv2.namedWindow('gray')   #窗口名
cv2.setMouseCallback("gray",mouse)   #鼠标事件
while True:
    cv2.imshow("gray",img)
    if cv2.waitKey(1)==27:
        break
cv2.destroyAllWindows()

原图

效果图

您可能感兴趣的与本文相关的镜像

EmotiVoice

EmotiVoice

AI应用

EmotiVoice是由网易有道AI算法团队开源的一块国产TTS语音合成引擎,支持中英文双语,包含2000多种不同的音色,以及特色的情感合成功能,支持合成包含快乐、兴奋、悲伤、愤怒等广泛情感的语音。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值