在python open中查找图像的所有X和Y坐标

2024-04-19 17:57:48 发布

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

我是opencv python的初学者。我想得到代码中提到的感兴趣区域的所有X和Y坐标,并将其存储在数组中。有人能告诉我怎么进行吗?我可以运行代码,但没有显示任何结果。

用于检测所有X和Y坐标的图像

下面是我编写的示例代码

import cv2
import numpy as np
import matplotlib.pyplot as plt
import imutils
img = cv2.imread("/home/harikrishnan/Desktop/image.jpg",0)
img1 = imutils.resize(img)
img2 = img1[197:373,181:300]  #roi of the image
ans = []
for y in range(0, img2.shape[0]):  #looping through each rows
     for x in range(0, img2.shape[1]): #looping through each column
            if img2[y, x] != 0:
                  ans = ans + [[x, y]]
ans = np.array(ans)
print ans

Tags: 代码inimageimportimgforasnp
2条回答

在代码中,您使用的是一个非常耗时的for循环。您可以使用快速而灵活的numpy库。

import cv2
import numpy as np
import matplotlib.pyplot as plt
import imutils
img = cv2.imread("/home/harikrishnan/Desktop/image.jpg",0)
img1 = imutils.resize(img)
img2 = img1[197:373,181:300]  #roi of the image

indices = np.where(img2!= [0])
coordinates = zip(indices[0], indices[1])
  • 我使用numpy.where()方法检索两个数组的元组索引,其中第一个数组包含白点的x坐标,第二个数组包含白点的y坐标。

indices返回:

(array([  1,   1,   2, ..., 637, 638, 638], dtype=int64),
 array([292, 298, 292, ...,  52,  49,  52], dtype=int64))
  • 然后我使用zip()方法获得包含这些点的元组列表。

打印coordinates会给我一个带有边的坐标列表:

[(1, 292), (1, 298), (2, 292), .....(8, 289), (8, 295), (9, 289), (9, 295), (10, 288)] 

这篇文章让你知道如何获得图像的像素 http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_core/py_basic_ops/py_basic_ops.html

如果你只是在一个嵌套的for循环中迭代图像,你可以对所说的像素执行任何你想执行的操作,例如,如果颜色不是白色,则向数组中添加x和y

编辑:我读了克里斯对XY问题的评论,但我同意,你有没有试过也没用的东西,希望我们帮忙解决?

相关问题 更多 >