首页 > 解决方案 > 在图像中的一组点周围寻找不同的边界

问题描述

我有一个看起来像这样的图像: 这是图像

我需要在这些点周围制作边界,以便将它们分成簇。例如,图像的中心是一个区域。另一个区域可以是图像的顶部。我怎样才能做到这一点,最好用python?

标签: pythonimageopencv

解决方案


这是在 Python/OpenCV 中执行此操作的一种方法。

 - Read the input as unchanged, since it has transparency
 - Separate the base image and the alpha channel
 - Mask the base image with the alpha channel so as to make the white outer region with the text into all black
 - Convert that image into grayscale and then into black/white
 - Apply morphology close to connect all the dots in the regions
 - Find all contours larger than some minimum area
 - Draw the contours on the base image
 - Save the results


输入:

在此处输入图像描述

import cv2
import numpy as np

# read image with transparency
image = cv2.imread("dots.png", cv2.IMREAD_UNCHANGED)

# separate base image and alpha channel and make background under transparency into black to remove white border and text
base = image[:,:,0:3]
alpha = image[:,:,3]
alpha = cv2.merge([alpha,alpha,alpha])
img = cv2.bitwise_and(base, alpha)

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#do threshold on gray image
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]

# apply morphology close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# Get contours
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
result = base.copy()
for c in cnts:
    area = cv2.contourArea(c)
    if area > 100:
        cv2.drawContours(result, [c], -1, (0, 255, 0), 1)

# display it
cv2.imshow("BASE", base)
cv2.imshow("BLACKENED", img)
cv2.imshow("CLOSED", close)
cv2.imshow("RESULT", result)
cv2.waitKey(0)

# write results to disk
cv2.imwrite("dots_blackened.png", img)
cv2.imwrite("dots_closed.png", close)
cv2.imwrite("dots_clusters.png", result)


透明度变黑的基础图像:

在此处输入图像描述

形态关闭图像:

在此处输入图像描述

基本图像上的轮廓:

在此处输入图像描述


推荐阅读