2

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 
4
  • 2
    I'm confused. What does "all the X and Y coordinates of pixels" mean? Isn't that just from 0 to the width of the image × from 0 to the height of the image? What are you trying to accomplish here? This sounds like an XY problem. Commented May 19, 2017 at 11:17
  • 1
    X, Y coordinates of what ??? Commented May 19, 2017 at 12:42
  • @YvesDaoust of all pixels of the image or entire image. Commented May 19, 2017 at 16:54
  • They are (0,0,(1,0)... (W-1,0), (0, 1), (1,1), (W-1,1)... (0,H-1), (1,H-1),... (W-1,H-1) Commented May 20, 2017 at 8:43

1 Answer 1

4

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)] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.