天天看點

OpenCV GrabCut算法 物體分割(python語言)

import numpy as np
import cv2
from matplotlib import pyplot as plt

imgpath = 'G:/Python_code/OpenCVStudy/images/grabcut.jpg'
img = cv2.imread(imgpath)

# 預先繪制圖檔
fig = plt.figure()
plt.subplot(121), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.subplot(122), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.colorbar()
plt.show()


def OnClick(event):
    # 擷取當滑鼠"按下"的時候,滑鼠的位置
    global Coords1x, Coords1y
    if event.button == 1:
        Coords1x = int(event.xdata)
        Coords1y = int(event.ydata)
        # print("1x1y" + str(Coords1x) + str(Coords1y))


def OnMouseMotion(event):
    # 擷取當滑鼠"移動"的時候,滑鼠的位置
    global Coords2x, Coords2y
    if event.button == 1:
        Coords2x = int(event.xdata)
        Coords2y = int(event.ydata)
        # print("2x2y" + str(Coords2x) + str(Coords2y))

def OnMouseRelease(event):
    if event.button == 1:
        fig = plt.gca()
        img = cv2.imread(imgpath)
        # 建立一個與所加載圖像同形狀的Mask
        mask = np.zeros(img.shape[:2], np.uint8)

        # 算法内部使用的數組,你必須建立兩個np.float64 類型的0數組,大小是(1, 65)
        bgdModel = np.zeros((1, 65), np.float64)
        fgdModel = np.zeros((1, 65), np.float64)

        # 計算人工前景的矩形區域(rect.x,rect.y,rect.width,rect.height)
        rect = (Coords1x, Coords1y, Coords2x - Coords1x, Coords2y - Coords1y)
        print(rect)
        iterCount = 5
        cv2.grabCut(img, mask, rect, bgdModel, fgdModel, iterCount, cv2.GC_INIT_WITH_RECT)

        mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
        img = img * mask2[:, :, np.newaxis]
        plt.subplot(121), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        plt.subplot(122), plt.imshow(
            cv2.cvtColor(cv2.imread(imgpath), cv2.COLOR_BGR2RGB))
        fig.figure.canvas.draw()


# 連接配接滑鼠點選事件
fig.canvas.mpl_connect('button_press_event', OnClick)
# 連接配接滑鼠移動事件
fig.canvas.mpl_connect('motion_notify_event', OnMouseMotion)
fig.canvas.mpl_connect('button_release_event', OnMouseRelease)
           

使用方法,在圖檔上用矩形框出你選擇的物體即可。

效果圖如下:

OpenCV GrabCut算法 物體分割(python語言)