Return brown percentage in image

Asked

Viewed 86 times

0

I have a code where I take a video and save an image every 20 frames and I take a slice of that image, until then I was able to do it, but I need to analyze if they have pixels with the same or darker shade of brown than this: RGB 194, 187, 138 and I have no idea how to do this, how to detect percentage of brown color with this specific RGB?

That’s my code so far

import cv2 
import os
import numpy as np

# Read the video from specified path 
cam = cv2.VideoCapture("D:/outpy.avi") 

currentframe = 0
x = 20
while(True): 

    # reading from frame 
    ret,frame = cam.read() 

    if ret: 
        # if video is still left continue creating images 
        name = 'D:/' + str(currentframe) + '.png'
        print ('Creating...' + name) 

        # writing the extracted images
        if currentframe == x:
            cv2.imwrite(name, frame)
            imagem = cv2.imread("D:/{}.png".format(x))
            fatia = imagem[0:150, 150:300]


            x = x + 20
        if cv2.waitKey(25) & 0xFF == ord('q'):
            break

        # increasing counter so that it will 
        # show how many frames are created 
        currentframe += 1
    else: 
        break

# Release all space and windows once done 
cam.release() 
cv2.destroyAllWindows()

1 answer

0

when I want to detect % of a certain color in my image you do so:

import numpy as np
import cv2

img = cv2.imread('J9MbW.jpg')

brown = [194, 187, 138]  # RGB
diff = 20
boundaries = [([brown[2]-diff, brown[1]-diff, brown[0]-diff],
               [brown[2]+diff, brown[1]+diff, brown[0]+diff])]
# in order BGR as opencv represents images as numpy arrays in reverse order

for (lower, upper) in boundaries:
    lower = np.array(lower, dtype=np.uint8)
    upper = np.array(upper, dtype=np.uint8)
    mask = cv2.inRange(img, lower, upper)
    output = cv2.bitwise_and(img, img, mask=mask)

    ratio_brown = cv2.countNonZero(mask)/(img.size/3)
    print('brown pixel percentage:', np.round(ratio_brown*100, 2))

    cv2.imshow("images", np.hstack([img, output]))
    cv2.waitKey(0)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.