0

I have the following code:

import cv2

import math

import numpy as np

img=cv2.imread("/home/lenovo/Desktop/road/1.jpg")

img1=cv2.resize(img,(28,28))

print(img1.shape)

img2=img1[int(0.2*img1.shape[0]):-1]

img_gauss=cv2.GaussianBlur(img2, (49,49),sigmaX=2,sigmaY=2)

img_median=cv2.medianBlur(img_gauss,31)

img_diff=img_gauss-img_median+127

img_thres=img_diff

for i in range(img_thres.shape[0]):

    for j in range(img_thres.shape[1]):

        if(img_thres[i,j]>150):

            img_thres[i,j]=255

        else:

            img_thres[i,j]=0

kernel = np.ones((3,3),np.uint8)

erosion = cv2.erode(img_diff,kernel,iterations = 2)

dil = cv2.dilate(erosion,kernel,iterations = 2)

cv2.imshow("image",dil)

cv2.waitKey(0)

My error is:

if(img_thres[i,j]>150):

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
rayryeng
  • 102,964
  • 22
  • 184
  • 193
Ganesh Dev
  • 19
  • 2
  • 6

1 Answers1

1

It looks like you are loading in a colour image but the input is expected to be grayscale. When doing img_thresh[i,j] for a colour image, this will return a three-element array that corresponds to the RGB colour values at location (i, j) thus producing that error. You can first solve the problem by ensuring that the image is loaded in as grayscale:

img=cv2.imread("/home/lenovo/Desktop/road/1.jpg", 0)

In addition, you can replace the double for loops with vectorized operations. Instead you can do:

img_thres = 255*((img_diff > 150).astype(np.uint8))

Once you do the above two changes your code should work.

rayryeng
  • 102,964
  • 22
  • 184
  • 193