Issue
I want to calculate the total number of pixels from a image for specific color witch will have all Sade of that specific color for example blue its will check all shade of blue and will return Total count of blue pixels
What is typed but its checking for blue not for shades of blue
from PIL import Image
im = Image.open('rin_test/Images33.png')
black = 0
red = 0
for pixel in im.getdata():
if pixel == (30,144,255): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so
blue += 1
print('blue=' + str(blue))
Solution
I would suggest using a range of hues in HSV color space in Python/OpenCV to get a mask. Then count the number of non-zero values in the mask.
Input:
import cv2
import numpy as np
# load image
img = cv2.imread('blue_bag.png')
# convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)
# create mask for blue color in hsv
# blue is 240 in range 0 to 360, so for opencv it would be 120
lower = (100,100,100)
upper = (160,255,255)
mask = cv2.inRange(hsv, lower, upper)
# count non-zero pixels in mask
count=np.count_nonzero(mask)
print('count:', count)
# save output
cv2.imwrite('blue_bag_mask.png', mask)
# Display various images to see the steps
cv2.imshow('mask',mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
Mask:
count: 34231
Answered By - fmw42 Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.