Finding all the X and Y coordinates of an image in python opencv

我的未来我决定 提交于 2020-02-29 09:16:22

问题


I am a beginner in opencv-python. I want to get all the X and Y coordinates of for the region of the interest mentioned in the code and store it in an array. Can anyone give me an idea on how to proceed? I was able to run the code, but is not showing any results.

Image for detecting all the X and Y coordinates

The sample code i wrote is written below,

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

回答1:


In your code you are using a for loop which is time consuming. You could rather make use of the fast and agile numpy library.

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])
  • I used the numpy.where() method to retrieve a tuple indices of two arrays where the first array contains the x-coordinates of the white points and the second array contains the y-coordinates of the white pixels.

indices returns:

(array([  1,   1,   2, ..., 637, 638, 638], dtype=int64),
 array([292, 298, 292, ...,  52,  49,  52], dtype=int64))
  • I then used the zip() method to get a list of tuples containing those points.

Printing coordinates gives me a list of coordinates with edges:

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



回答2:


this post lets you know how to get the pixel of an image http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_core/py_basic_ops/py_basic_ops.html

if you just iterate over the image in a nested for-loop you can perform whatever operation you want on said pixel eg, add x and y to an array if the colour isnt white

EDIT: i had to read up on what Chris commenting on the post meant by XY Problem but i agree, is there something youve tried and hasnt worked that youd like us to help fix?



来源:https://stackoverflow.com/questions/44068654/finding-all-the-x-and-y-coordinates-of-an-image-in-python-opencv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!