【问题标题】:Plotting pixels and contours when XY coordinates are known在已知 XY 坐标时绘制像素和轮廓
【发布时间】:2020-02-13 01:10:20
【问题描述】:

我在 python 中使用 Open CV,并从轮廓和点多边形测试操作中提取了一些点。 (我基本上使用 pointpolygon 测试来检查某些像素是否在轮廓内)。 现在我得到了分数,但我想直观地确认我所拥有的点是否实际上在轮廓内。怎么办? 理想情况下,我想先绘制轮廓,然后绘制提取的像素。 我可以使用drawcontours函数绘制轮廓,但是为了绘制这些点,我知道的唯一方法是plt.scatter,它更多地使用matplotlib而不是opencv。

我处理这个问题的方式可能存在根本性的错误,因为感觉应该有一种更简单的方法来做到这一点,而我却错过了。这是到目前为止我所拥有的代码片段以供参考。

编辑:根据 Mark Setchell 的建议,在我使用 image[x,y] 为特定像素设置颜色的地方添加了一个代码 sn-p。但是,在我的情况下,(x,y) 是笛卡尔坐标,如果我将其作为图像的像素坐标,它将不起作用。

import numpy as np
import cv2
import matplotlib.pyplot as plt

img = cv2.imread('ti.png',1)
plt.imshow(img)

ret, thresh = cv2.threshold(img, 250, 300, cv2.THRESH_BINARY_INV)

greySrc = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
laplacianSrc= cv2.Laplacian(greySrc, cv2.CV_8U, greySrc, ksize = 5)
contours, hierarchy=cv2.findContours(laplacianSrc, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


indices = np.where(img!= [0])
coordinates = zip(indices[0], indices[1])
pts=list(coordinates)

in_or_out=[cv2.pointPolygonTest(contours[0],point,measureDist=False) for point in pts]
pts_ins_ctr=[x for x, y in zip(pts, in_or_out) if y == 1]
xi=[pts_ins_ctr[i][0] for i in range(len(pts_ins_ctr))]
yi=[pts_ins_ctr[i][1] for i in range(len(pts_ins_ctr))]

img[np.array(pts_ins_ctr)]=np.array([255,0,0],dtype=np.uint8)
plt.imshow(img)

输入图片

输出图片

【问题讨论】:

  • cv2.drawcontour() 用于轮廓。 cv2.rectangle() 或 cv2.line() 或 cv2.circle 有 2 个点,间隔 1 个像素或 1 个像素的半径。或者使用 numpy 将 1 像素的图像插入到您的图像中。
  • 如果您只想更改给定像素的颜色,请参阅opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/…
  • 谢谢@fmw42 我知道drawcontour、矩形、线条等,但我有一系列X、Y坐标(pts_ins_contour)。我如何绘制它们?
  • image[y,x]=255 将使该像素变为白色。
  • @MarkSetchell 这实际上是一个很好的方法,我很高兴学习,但像素坐标与 x,y 坐标不同。所以它弄乱了我的整个形象。 (像素数与图像的 x,y 坐标数不同)

标签: python opencv point-in-polygon


【解决方案1】:

这个解决了。谢谢@MarkSetchell

for pts in pts_ins_ctr:
    img[tuple(reversed(pts))]=[255,0,0]

两件事奏效了

  1. 在循环中分配颜色,而不是尝试一次分配所有颜色。
  2. im[y,x]=pix_color(正如标记所评论的那样)

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 2020-06-19
    • 1970-01-01
    • 2019-02-12
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多