首页 > 解决方案 > 基于OpenCV中的线分割图像和标签分割

问题描述

我有一个可以用轮廓线分割的图像。我想拆分它并在其质心上标记每一块。我对如何在其质心上标记轮廓有一个好主意,但不知道如何获得该轮廓。

在此处输入图像描述

import cv2

img = cv2.imread(path)

contours = get_contours() # this I don't know how to do

def get_centroid(c):
    positions = []
    M = cv2.moments(c)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    return (cx,cy)

centroids = [get_centroid(c) for c in contours]

for ix, centroid in enumerate(centroids):
    cv2.putText(
        img,
        text=str(ix),
        org=centroid,
        fontFace=cv2.FONT_HERSHEY_SIMPLEX,
        fontScale=1,
        color=(0, 0, 0),
        thickness=1,
        lineType=cv2.LINE_AA,
    )

标签: pythonopencvimage-processingcomputer-visionopencv-python

解决方案


你可以用cv2.findContours这个。这是一个示例方法

image = cv2.imread(path)
### converting to gray scale
gray_scale=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
### applying blur layer to connect nearby pixels
blur = cv2.GaussianBlur(gray_scale,(5,5),0)
### binarising
th1,img_bin=cv2.threshold(blur,150,225,cv2.THRESH_OTSU)
### finding contours
contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
### draw all contours
image = cv2.drawContours(image, contours, -1, (0, 255, 0), 2)

def get_centroid(c):
    positions = []
    M = cv2.moments(c)
    cx = int(M['m10']/M['m00'])
    cy = int(M['m01']/M['m00'])
    return (cx,cy)

centroids = [get_centroid(c) for c in contours]

for x,y in centroids:
    image = cv2.circle(image, (x,y), radius=3, color=(0, 0, 255), thickness=-1)

这是我们得到的输出。绿色表示检测到的轮廓,蓝点是质心。

质心标记


推荐阅读