Python 打开 CV - 获取区域坐标

Python Open CV - Get coordinates of region

我是图像处理(和 openCV)的初学者。将分水岭算法应用于图像后,获得的输出是这样的 -

是否可以将区域的坐标分割出来?

使用的代码是这样的(如果你想看的话)-

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


img = cv2.imread('input.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

# noise removal
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)

# sure background area
sure_bg = cv2.dilate(opening,kernel,iterations=3)

# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening,cv2.cv.CV_DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)

# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)

# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)

# Add one to all labels so that sure background is not 0, but 1
markers = markers+1

# Now, mark the region of unknown with zero
markers[unknown==255] = 0

markers = cv2.watershed(img,markers)
img[markers == -1] = [255,0,0]

plt.imshow(img)
plt.show()

是否有任何函数或算法可以提取分离出的彩色区域的坐标?任何帮助将不胜感激!

在这一行之后:

markers = cv2.watershed(img,markers)

markers是一张所有区域都被分割的图像,每个区域的像素值都是一个大于0的整数(label)。背景有label 0,边界有标签 -1。

您已经知道 connectedComponents 返回的 ret 的标签数。

您需要一个数据结构来包含每个区域的点。例如,每个区域的点将放在一个点数组中。你需要几个这样的(每个区域),所以另一个数组。

所以,如果你想找到每个区域的像素,你可以这样做:

1) 扫描图像并将点附加到点数组,其中每个点数组将包含同一区域的点

// Pseudocode

"labels" is an array of an array of points
initialize labels size to "ret", the length of each array of points is 0.

for r = 1 : markers.rows
    for c = 1 : markers.cols
        value = markers(r,c) 
        if(value > 0)
            labels{value-1}.append(Point(c,r)) // r = y, c = x
        end
    end
end

2) 为每个label值生成mask,收集mask中的点

// Pseudocode

"labels" is an array of an array of points
initialize labels size to "ret", the length of each array of points is 0.

for value = 1 : ret-1
    mask = (markers == value)
    labels{value-1} = all points in the mask // You can use cv::boxPoints(...) for this
end

第一种方法可能要快得多,第二种方法更容易实施。抱歉,但我不能给你 Python 代码(C++ 会好得多 :D ),但你应该找到出路。

希望对你有帮助