Skip to content
Advertisement

numpy.AxisError: axis 2 is out of bounds for array of dimension 0

I’m creating a program the requires a black and white image and two arrays containing the X and Y coordinates of both black and white pixels respectively. I have a program that utilizes OpenCV and binary thresholding to create a black and white image (code source). Hear is the code I have in full so far.

#Load image
im = cv2.imread('image.png')

#create grey image
grayImage = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

#create full black and white image
(thresh, blackAndWhiteImage) = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY)

#Define black and white
black = [0,0,0]
white = [255,255,255]

#Get X and Y coordinates of both black and white
Xb,Yb = np.where(np.all(blackAndWhiteImage==black,axis=2))
Xw,Yw = np.where(np.all(blackAndWhiteImage==white,axis=2))

#combine x and y
Bzipped = np.column_stack((Xb,Yb))
Wzipped = np.column_stack((Xw,Yw))

#show
print(Bzipped,Wzipped)

The problem I have comes up at these lines

Xb,Yb = np.where(np.all(blackAndWhiteImage==black,axis=2))
Xw,Yw = np.where(np.all(blackAndWhiteImage==white,axis=2))

when the program is run the error numpy.AxisError: axis 2 is out of bounds for array of dimension 0 is shown.

What does this error mean and how can I fix the program?

Advertisement

Answer

Replace those two lines of code with the following lines:

#Black
(Xb, Yb) = np.where(blackAndWhiteImage==0)
#white
(Xw, Yw) = np.where(blackAndWhiteImage==255)

What’s happening here is that the blackAndWhiteImage is a binary image. Thus, it contains only one channel. Therefore, axis=2 is not valid for single channeled image and also you were comparing the image value to [0, 0, 0] or [255, 255, 255] that is not possible as the image contain values equal to 0 or 255 only.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement