python实现grabcut算法进行物体分割

GrabCut算法进行物体分割

GrabCut算法原理

(1)在图片中定义含有(一个或多个)物体的矩形。
(2)矩形外外的区域被自动认为是背景。
(3)对于用户定义的矩形区域,可用背景中的数据来区别它里面的前景和背景区域。
(4)用高斯混合模型(Gaussians Mixture Model,GMM)来对背景和前景建模,并将未定义的像素标记为可能的前景和背景。
(5)图像中的每一个像素都被看作通过虚拟边与周围像素的链接,而每条边都有一个属于前景或背景的概率,这基于它与周围像素颜色上的相似性。
(6)每一个像素(即算法中的节点)会与一个前景或背景节点链接。
(7)在节点完成链接后(可能与背景链接,也可能与前景链接),若节点之间的边属于不同终端(即一个节点属于前景,另一个节点属于背景),则会切断他们之间的边,这就能将图像各部分分割出来。

python实现GrabCut算法

(批量处理图片)

'''
grabcut算法进行物体分割
'''
import numpy as np
# from PIL import Image
import cv2
import os
from matplotlib import pyplot as plt

# img_prefix='.JPG'
# path="G:/Datasets/goldcion/train"
# def read_imgs(path):
#     files=os.listdir(path)
#     for file in files:
#         index = file.find('.')
#         prefix-file[index+1]
#         if prefix in img_prefix:
#             print(file)
#             return file
fp = open('G:/Datasets/goldcion/images_train.txt', 'r')
# img = Image.open('G:\\Datasets\\goldcion\\2-1-1.JPG')#返回一个Image对象
# print('宽:%d,高:%d'%(img.size[0],img.size[1]))
# img=img.resize((224,224))
for file in fp:
    file=file.strip("\n")
    file=file.split(' ')
    file=file[0]
    pth=file.split('/')
    pth1='G:/Datasets/goldcoin_seg/train/%s/'%pth[4]
    pth0=pth[4]+'/'+pth[5]
    img=cv2.imread(file)
    # img=cv2.imread('G:/Datasets/goldcion/2-1-1.JPG')
    img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC)
    mask=np.zeros(img.shape[:2],np.uint8)

    bgdModel=np.zeros((1,65),np.float64)
    fgdModel=np.zeros((1,65),np.float64)

    rect=(5,5,224,224)
    cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

    mask2=np.where((mask==2)|(mask==0),0,1).astype('uint8')
    img=img*mask2[:,:,np.newaxis]
    if not os.path.lexists(pth1):
        os.makedirs(pth1)

    cv2.imwrite('G:/Datasets/goldcoin_seg/train/%s'%pth0,img)#第一个参数是目标存放的名字,第二个参数是目标
# plt.subplot(121),plt.imshow(img)
# plt.title("grabcut"),plt.xticks([]),plt.yticks([])
# plt.subplot(122),plt.imshow(cv2.cvtColor(cv2.imread('G:/Datasets/goldcion/2-1-1.JPG'),cv2.COLOR_BGR2GRAY))
# plt.title("original"),plt.xticks([]),plt.yticks([])
# plt.show()
阈值分割是一种简单的图像分割方法,它将图像分为两个或多个不同区域,其中像素的灰度值高于或低于某个阈值。活动轮廓模型分割方法则使用数学模型来描述图像中的物体边界,并利用能量最小化算法来优化模型,从而得到物体的精确边界。 以下是用Python实现阈值分割和活动轮廓模型分割的代码: 阈值分割: ```python import cv2 # 读取图像 img = cv2.imread('image.png', 0) # 阈值分割 ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # 显示结果 cv2.imshow('image', thresh) cv2.waitKey(0) cv2.destroyAllWindows() ``` 活动轮廓模型分割: ```python import numpy as np import cv2 # 读取图像 img = cv2.imread('image.png', 0) # 初始化掩模和轮廓 mask = np.zeros(img.shape[:2], np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), np.float64) # 定义矩形框 rect = (50, 50, 300, 500) # 运行GrabCut算法 cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT) # 提取前景 mask2 = np.where((mask == 1) | (mask == 3), 255, 0).astype('uint8') res = cv2.bitwise_and(img, img, mask=mask2) # 显示结果 cv2.imshow('image', res) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这里的代码是使用OpenCV库来实现的。阈值分割使用了cv2.threshold()函数,而活动轮廓模型分割使用了cv2.grabCut()函数。在阈值分割中,我们将图像像素值高于127的部分设为255(白色),其他部分设为0(黑色)。在活动轮廓模型分割中,我们使用了GrabCut算法来提取图像中的前景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值