python - 基于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,
)
解决方案
你可以用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)
这是我们得到的输出。绿色表示检测到的轮廓,蓝点是质心。
推荐阅读
- firebase - Firestore 云功能在不部署功能的情况下不会触发
- ansible - ansible fetch模块的问题
- azure - 如何在发布构建期间用 configSource 替换连接字符串文件?
- c++ - 四阶 Adams-Moulton 方法 C++
- c# - WinForm C#中的CefSharp如何减小应用程序大小
- react-native - GooglePlacesAutocomplete 对地点列表内容的样式不起作用,无法包装地点 react-native
- wpf - WPF Datagrid 将 BorderBrush 添加到行导致行在 IsMouseOver 上移动
- c# - 在 Visual Studio 2019 中禁用工具提示
- python - 将下载的数据保存到 csv 不会添加扩展名 .csv
- c++ - c++ 空复制赋值运算符复制数据