PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

[FIXED] How to count number of pixels for specific color from Image Using python

 May 06, 2022     image, image-processing, opencv, python, python-imaging-library     No comments   

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))

Sample Image for blue color enter image description here


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:

enter image description here

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:

enter image description here

count: 34231


Answered By - fmw42
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing