首页 > 解决方案 > Python比较图像中哪个RGB值具有最多像素

问题描述

所以我正在使用openCV,我正在获取一个RGB值列表,将它们与图像中的像素选择进行比较,然后返回列表中哪个RGB值最多。我有一个名为 colorCalc.py 和 face.py 的文件。ColorCalc 只是方法,而 face 使用 Colorcalc.py 中的方法。我遇到的主要问题是函数 colorCheck,似乎第一个 if 语句似乎没有检查,因为它总是正确的,根据 colorCheck 计算的数字,它不应该是。face.py 脚本也包括在内,以防有人想复制我所做的一切。以下来自 ColorCalc.py

 def colorCheck(src,source):

    prevCount=0
    counter=0;
    ans=20

    for i in range(len(src)):
        counter=0
        for s in range(len(source)):

            if colorDifference(src[0][0],src[0][1],src[0][2],source[0,s,0],source[0,s,1], source[0,s,2])>2:
                counter= counter+1
                print("OKAY")
            if ans== 20:
                    prevCount=counter
                    counter=0

                    ans=src[0,3]
            elif counter>=prevCount:
                    prevCount=counter
                    counter=0
                    ans=src[0,3]

            #print(colorDifference(src[0][0],src[0][1],src[0][2],source[0,s,0],source[0,s,1],source[0,s,2]))       
    return ans

这只是创建了我要比较的数组,而下一个函数比较 RGB 值

def colorArray():
colArr=[[0 for x in range(3)] for y in range(12)]
#these colors are from darkest to lightest skin tone. The number at the end is to tell which value we are considering after sorting
#black skin
colArr[0]=[117,85,61,0]
colArr[1]=[159,136,121,1]
#bronze Skin
colArr[2]=[156,115,69,2]
colArr[3]=[182,157,69,3]
#medium brown skin
colArr[4]=[196,142,88,4]
colArr[5]=[217,181,149,5]
#light brown skin
colArr[6]=[220,180,119,6]
colArr[7]=[236,195,155,7]
#cream-colored skin
colArr[8]=[230,189,149,8]
colArr[9]=[239,210,180,9]
#pale skin
colArr[10]=[231,207,183,10]
colArr[11]=[240,222,205,11]

colArr= numpy.asarray(colArr)
return colArr

def colorDifference(r,g,b,r1,g1,b1):
red= abs((r-r1)**2)
blue= abs((b-b1)**2)
green= abs((g-g1**2))
answer=math.sqrt(red+blue+green)

return answer;

接下来是我实际使用它的方式,即 face.py 脚本

    import numpy as np
    import cv2 as cv
    import math
    import colorCalc as col

    #load xml files
    face_cascade = cv.CascadeClassifier('C:\Program 
    Files\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
    eye_cascade = cv.CascadeClassifier('C:\Program 
    Files\opencv\sources\data\haarcascades\haarcascade_eye.xml')

#define image and convert to grayscale
pic= cv.imread('face.jpg')

gray = cv.imread('face.jpg',0)

img= pic
color = np.array([])

#scan for faces and draw rectangle
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
x1= faces[0][0]
x2= faces[0][2]
y1= faces[0][1]
y2= faces[0][3]

这需要使用 openCV 创建的 numpyArray 的一部分

source=img[x1:x1+x2, y1:y1+y2, :]

虽然这实际上调用了函数

 colArr=col.colorArray()


    answer=col.colorCheck(colArr,source)

    print(answer)

标签: pythonopencv

解决方案


你有一个错字。更改此行

green= abs((g-g1**2))

green= abs((g-g1)**2)

推荐阅读