python - 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)
解决方案
你有一个错字。更改此行
green= abs((g-g1**2))
至
green= abs((g-g1)**2)
推荐阅读
- dialogflow-es - Dialogflow Fulfillment 响应似乎不适用于丰富响应(基本卡)和 OutputContext 或后续事件
- python - 我应该何时使用 DateTime(timezone=True) 以及何时使用 TIMESTAMP(timezone=True)?
- python - 如何在不使用全局变量的情况下完成同样的事情?
- javascript - 单击时冻结页面
- python - 在北极图书馆存储和获取多个股票
- scala - scala - 交换列表中的前 2 个元素
- python-3.x - .pyw 文件的 shebang 行是什么?
- java - 关于凸包中最远点的问题(在java中)
- prolog - 在 ECLiPSe-CLP 中写入圆形区域有错误
- python - Pandas 在 groupby 之后获取所有行的最小值和最大值