Home>

After masking the image of the red sphere, labeling is performed to obtain the center coordinates of the processed product, and X = [[x coordinate 1, y coordinate 1], [x coordinate 2, y coordinate 2], [x coordinate 3, y I'm thinking of making a list like [Coordinates 3] ,,,] and outputting the x-coordinate and y-coordinate graphs with matplotlib, but I get an error.


akamaru.jpg

The content of the error is that X is not defined, how can I define X? Or is it the wrong way to set up the iteration process in the first place?

X = np.array (X)
NameError: name'X' is not defined
Corresponding source code
import cv2
import numpy as np
import matplotlib.pyplot as plt

def red_detect (img):
    #Convert to HSV color space
    hsv = cv2.cvtColor (img, cv2.COLOR_BGR2HSV)
    # Red HSV range 1
    hsv_min = np.array ([0,127,0])
    hsv_max = np.array ([30,255,255])
    mask1 = cv2.inRange (hsv, hsv_min, hsv_max)
    # Red HSV range 2
    hsv_min = np.array ([150,127,0])
    hsv_max = np.array ([179,255,255])
    mask2 = cv2.inRange (hsv, hsv_min, hsv_max)
    return mask1 + mask2

img_path = "akamaru.jpg"
img = cv2.imread (img_path)
# Red detection
mask = red_detect (img)
kernel = np.ones ((5,5), np.uint8)
mask = cv2.erode (mask, kernel, iterations = 3)
# Labeling process
label = cv2.connectedComponentsWithStats (mask)
# Extract object information by item
n = label [0] ―― 1
data = np.delete (label [2], 0, 0)
center = np.delete (label [3], 0, 0)
def oo ():
  X = []
  #Get object information
  for i in range (n):
    #Display the coordinates of the center of gravity of each object
    print ("ID:" + str (i + 1), "", "X:" + str (int (center [i] [0])), "", "Y:" + str (int (center [center]) i] [1]))))
    X + = [int (center [i] [0]), int (center [i] [1])]
    i + = 1
    if i == n:
      break
  return X
if __name__ == "__main__":
  oo ()
X = np.array (X)
plt.figure ()
plt.title ('data')
plt.scatter (X [:, 0], X [:, 1], marker ='o', s = 75, color ='black')
plt.show ()
Supplementary information (FW/tool version, etc.)

Operating environment
Python3.8
Windows 10
OPENCV 4.4.0

I haven't deepened my understanding so much, so I may be doing something strange in some places, but I would appreciate it if you could teach me.

  • Answer # 1

    How about the following corrections?

    if __name__ == "__main__":
      X = oo ()
      X = np.array (X)
      plt.figure ()
      plt.title ('data')
      plt.scatter (X [:, 0], X [:, 1],
      marker ='o', s = 75, color ='black')
      plt.show ()