N.Panda
N.Panda

Reputation: 1

I'm trying to display the percentage of red color in my image with OpenCV and Python

I'm fairly new to both OpenCV and Python and I'm trying to calculate the number of red pixels and display it as a percent. However, it keeps displaying 0% even though there is a lot of red in the picture. Could someone please help me out?

This is what I have so far,

import cv2
import numpy as np

img = cv2.imread('roi.jpg')
size = img.size


RED_MIN = np.array([0,0,128], np.uint8)
RED_MAX = np.array([250, 250, 255], np.uint8)


dstr = cv2.inRange(img, RED_MIN, RED_MAX)
no_red = cv2.countNonZero(dstr)
frac_red = np.divide((int(no_red)),(int(size)))
percent_red = np.multiply((int(frac_red)), 100)
print('Red: ' + str(percent_red) + '%')

Upvotes: 0

Views: 1760

Answers (1)

ZdaR
ZdaR

Reputation: 22954

The bug seems to be in frac_red = np.divide((int(no_red)),(int(size))), As you are explicitly converting both the operands to int before passing them to np.divide(), which would also return an int if both the operands are int, To get the precise decimal percentage, you need to pass either one or both of them as float:

frac_red = np.divide(float(no_red), int(size))

# Your current Scenario
In [5]: np.divide(3, 8)
Out[5]: 0

# Expected Scenario
In [7]: np.divide(3.0, 8)
Out[7]: 0.375

Upvotes: 2

Related Questions