根据像素颜色的变化定位坐标

2024-06-01 12:47:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图定位图像中的特定坐标。我有一个图像,只包含两种颜色,粉红色和黑色,如图所示。如果我知道粉色区域中的(x,y)坐标(中心用黄点标记),我如何才能找到粉色区域边界中的坐标(如边界上的黄点所示)

enter image description here

注:黄点不是图像的一部分,我用它来表示感兴趣的区域

我只是想知道除了嵌套for循环之外,是否有其他更快更好的方法来实现这一点,因为我需要在图像的多个区域中找到边界坐标,这可能会真正减慢处理过程

谢谢大家!


Tags: 方法标记定位图像区域for颜色中心
2条回答

下面是使用Python/OpenCV和Numpy的一种方法

  • 读取输入
  • 变灰
  • 大津阈值
  • 裁剪包含中心的行
  • 获取行中所有白色的坐标
  • 打印第一个和最后一个坐标
  • 在输入上画线
  • 保存结果

输入:

enter image description here

import cv2
import numpy as np

# load image
img = cv2.imread("pink_blob.png")
hh, ww = img.shape[:2]

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

# threshold
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# center coords
center = (115,82)
cy = center[1]

# crop row at y center
row = thresh[cy:cy+1, 0:ww]

# get coordinates along row where it is white
# swap x and y between numpy and opencv coords
coords = np.argwhere(row==255)
num_coords = len(coords)
start = coords[0]
end = coords[num_coords-1]
start_pt = (start[1],cy)
end_pt = (end[1],cy)

print(start_pt)
print(end_pt)

# draw line from start to end coordinates on input
result = img.copy()
cv2.line(result, start_pt, end_pt, (255,255,255), 1)

# save result
cv2.imwrite('pink_blob_line.png', result)

# show result
cv2.imshow('result', result)
cv2.waitKey(0)

Start and End Coordinates:

(67, 82)
(160, 82)

输入图像上的行:

enter image description here

首先,找到图像中粉红色区域的轮廓。您可以首先对图像应用Otsu的阈值,然后使用cv2.findOntours()查找轮廓

然后在轮廓边界点中,找到与中心像素具有相同y坐标的点

其中,x坐标最大的点为右侧点,x坐标最小的点为左侧点

相关问题 更多 >