python - 在图像中的一组点周围寻找不同的边界
解决方案
这是在 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)
透明度变黑的基础图像:
形态关闭图像:
基本图像上的轮廓:
推荐阅读
- c++ - Windows - 从挂起的进程中卸载 dll
- node.js - 我从 Qrcode monkey APi 获得一个 png 图像作为响应,我需要将该图像保存在我后端的一个文件夹中(response.data 是一个 png 文件)
- python - 我可以过滤镶木地板吗?
- python - Python 类数据框语法高亮错误
- wordpress - Nginx Multisite Wordpress 加载资源失败:服务器响应状态为 503
- angular - Angular:从同一项目/分支上的两台不同 PCS 构建的 ng 在 index.html 中生成两个不同版本的脚本,从而导致错误
- javascript - Ag 网格阻止访问 React 状态变量的当前值
- or-tools - OR-Tools VRP 中是否可以有非无状态维度?
- node.js - Sequelize 查询错误?查找参数
- c++ - OpenGL 4.5:将纹理绑定读回片段着色器中设置的图像缓冲区时出错