python - 找到两种颜色之间的交线
问题描述
我试图找到一组与此类似的图像的绿色和蓝色之间的交集:
所以我需要的是这样的东西:
因为在那之后我需要使用轮廓进行一些微积分,所以我想知道是否有可能将曲线的点放在数组或其他东西中......但我不知道这是否可能。我试着做面具,但我不认为它会起作用......这是代码:
lower_val = np.array([0, 0, 0])
upper_val = np.array([150, 255, 150])
mask = cv2.inRange(image, lower_val, upper_val)
only_lumen = cv2.bitwise_and(image, image, mask=mask)
gray = cv2.cvtColor(only_lumen, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
thresh = 255 - thresh
这就是我试图显示这些点的方式:
x, y = [i[0] for i in pts_list], [i[1] for i in pts_list]
max_x, max_y = max(x), max(y)
image = np.zeros((max_y + 1, max_x + 1))
for i in range(len(pts_list)):
image[max_y - y[i], x[i]] = 1
我不明白为什么这些点会在一个角落里相遇,为什么背景是紫色的......应该在中间的线条
解决方案
现在,我将为您提供可以尝试的最简单的解决方案(可以改进很多):
边界像素(获得蒙版后)将彼此相邻,但如果您希望最小为 1 个像素宽度的边界,则必须选择一侧。对此的替代方法是设置搜索内核并使用形态学根据您的搜索内核扩展您的颜色蒙版。扩张蒙版中的公共点将是您可以通过简单地执行按位与来提取的邻域点。
# Define the color ranges for each color of interest for creating masks.
COLOR1_RANGE = [(30, 0, 0), (255, 50, 50)] # Blue in BGR, [(low), (high)].
COLOR2_RANGE = [(0, 30, 0), (50, 255, 50)] # Green in BGR, [(low), (high)].
# Create masks:
color1_mask = cv2.inRange(self.img, COLOR1_RANGE[0], COLOR1_RANGE[1])
color2_mask = cv2.inRange(self.img, COLOR2_RANGE[0], COLOR2_RANGE[1])
# Adjust according to your adjacency requirement.
kernel = np.ones((3, 3), dtype=np.uint8)
# Dilating masks to expand boundary.
color1_mask = cv2.dilate(color1_mask, kernel, iterations=1)
color2_mask = cv2.dilate(color2_mask, kernel, iterations=1)
# Required points now will have both color's mask val as 255.
common = cv2.bitwise_and(color1_mask, color2_mask)
# Common is binary np.uint8 image, min = 0, max = 255.
# SOME_THRESHOLD can be anything within the above range. (not needed though)
# Extract/Use it in whatever way you want it.
intersection_points = np.where(common > SOME_THRESHOLD)
# Say you want these points in a list form, then you can do this.
pts_list = [[r, c] for r, c in zip(*intersection_points)]
print(pts_list)
一些示例输出:
输出点为列表(部分):
pts_list = [[99, 104], [99, 105], [100, 104], [100, 105], [100, 106], ...]
输出点为列表(部分):
pts_list = [[127, 309], [127, 310], [127, 311], [127, 312], [127, 313], ...]
更新 1:
我对代码注释做了一些小改动,使其更易于理解。
推荐阅读
- android - 如何从firebase获取特定的子数据
- amazon-ec2 - 新 AMI 发布时 Terraform 重新创建的 EC2 实例
- eclipse - 从 Indigo 升级到 Luna Eclipse 时的配置
- node.js - 如何将生成的文件从节点应用程序推送到 github 存储库?
- python - bfs 遍历二叉树的性能
- excel - 如何从谷歌表格单元格中读取评论?
- multithreading - 如何通过多线程格式化多个文件
- c# - 自定义 AuthorizeAttribute 未实现
- python - 在 PyCharm 中使用 Python 环境和解释器
- dart - 为什么依赖项下的`pubspec.yaml`文件中有一个^ Cap符号