Home > Software design >  python: opencv,some issue when count pixel
python: opencv,some issue when count pixel

Time:12-10

I use opencv to count the number of white and black pixels of picture(I have convert them into black and white image), and everytime I run my code it return the number is 0,and the code is

output_path = "/content/drive/MyDrive/dataset_demo/result_pic"

for pic in os.listdir(output_path):
  if pic.endswith('.jpg'):
    image = cv2.imread(pic,cv2.IMREAD_UNCHANGED)
    number_of_white_pix = np.sum(image == 255)
    number_of_black_pix = np.sum(image == 0)
    number_of_total = number_of_white_pix   number_of_black_pix
    number_of_ratio = number_of_white_pix / number_of_black_pix
    print(number_of_total)

CodePudding user response:

The pic variable contains only the file name of the image, but cv2.imread needs the full path to the image in order to read it. You need to use the full path to the image when you call cv2.imread.

output_path = "/content/drive/MyDrive/dataset_demo/result_pic"

for pic in os.listdir(output_path):
  if pic.endswith('.jpg'):
    pic = os.path.join(output_path, pic) #full path to the image
    image = cv2.imread(pic,cv2.IMREAD_UNCHANGED)
    number_of_white_pix = np.sum(image == 255)
    number_of_black_pix = np.sum(image == 0)
    number_of_total = number_of_white_pix   number_of_black_pix
    number_of_ratio = number_of_white_pix / number_of_black_pix
    print(number_of_total)
  • Related