38

拿下抖音小姐姐,我写了个口红色号识别器!

 4 years ago
source link: http://developer.51cto.com/art/201909/603363.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

拿下抖音小姐姐,我写了个口红色号识别器!

对于广大“钢铁直男”的程序员来说,送什么礼物给女朋友一直是个世纪难题。

对于广大“钢铁直男”的程序员来说,送什么礼物给女朋友一直是个世纪难题。

b05f3a6606edb27dc2593d093d0cbf72.jpg-wh_651x-s_1390135750.jpg

图片来自 Pexels

其实哄女朋友开心最深的套路就是花式送口红,就问谁抵挡得住啊啊啊啊......

“没有什么问题是一支口红解决不了的,如果有,那就两支。”于是,直男们纷纷开始各种买口红、送口红……

毕竟李佳琦一句"OMG买它”,女朋友披头散发抢购,钱包就空了一半。

f091a2ca1be973155d39a2f7e4db5946.png

但是,口红色号千千万,选对了牌子才成功了一半。

快乐橙、伤心紫,姨妈红,鸡屎绿…直男眼里没什么区别的颜色,在女生眼里各种色调、质地细微的区别都能分析一清二楚。

f255196d6e05cd7130f273a429499207.png

那么,对于直男来说,怎么才能搞清楚如此多的口红色号呢?

我耗费一毫米发际线,琢磨了一下,做出了一个口红色号识别器,希望能帮大家在关键时刻把深刻的革命友谊再升华一下。

先来看看效果。让我们假设,小姐姐发来了一张美妆博主的美照,并暗示你,“人家也喜欢这个颜色。”

a9043b93f2773574af88912b68d2020f.jpg-wh_600x-s_2542221919.jpg

图片来自网络

这个时候,用我们的口红色号识别器,就能定位嘴唇,并迅速给出它的颜色隶属哪家品牌的哪个色号。

50e1caa02bbcf1fa68761ac3975a1411.jpg-wh_600x-s_3323238665.jpg

OMG!简直比李佳琦还准确!

1caf8b8dfb00040140d1e9aecf1119fe.png

好啦,废话不多说,马上开始教学时间!

来自 Github 的口红色号宇宙

要想识别口红色号,先得让机器知道到底都有哪些颜色。

听柜姐介绍,红色系有:“草莓红、铁锈红、枫叶红...”,其他还有“豆沙色、吃土色、番茄色...”

264c6158175f594a9abfb4fc9911f318.png

世界观还未建立完全就要开始土崩瓦解,这看着有区别吗?“豆沙色最为百搭,橘调的番茄色比较显白...”眼前的黑不是黑,你说的红是什么红?

a8eadfb8976f4d635fd50bd76b2f6855.jpg

还好,在万能的 Github 上找到了一个宝藏数据库“口红颜色可视化”,这个数据库堪比口红的色号宇宙,不仅囊括了当前最主流品牌的各种系列色号,还很良心的在色盘上排列了出来。

这个数据集是一个嵌套的字典数据结构,存为 json 串的形式,里面记录了每个口红品牌系列下不同口红色号的颜色 id、名称、和 16 进制颜色值。

直!男!救!星!有木有!

口红色号可视化链接:



  1. https://github.com/Ovilia/lipstick 

不过看着这密密麻麻的颜色,真心佩服各大口红品牌的文案高手,是怎么样区别每一个看不出区别的颜色,并且还要分别取名字的。

fa6e5871915a6a6576e5fc170a8c327e.jpg-wh_600x-s_619186030.jpg

傻傻分不清的我对 5 个品牌的不同系列做了一下统计和色号录入,于是,剩下的就交给计算机啦。

先用番茄做个实验?

既然有了如此完备的色号数据库,那么文摘菌就有了一个讨巧的方法:要想找到合适的色号,可以直接截取颜色,然后在数据库中进行比对。

这个方法非常好操作,在上唇色之前,我们不如先拿别的红色物品来练手。

比如,这里有一只番茄图片,你看这个番茄它又大又圆:

0a8a7744ab8d31851cd78160b8f4312b.jpg-wh_600x-s_1055769933.jpg

在其中截取了成色均匀、无高亮的矩形图片:

提取这张纯色图片的 RGB 值在技术上是可行的,getcolor.py 代码如下:



  1. import colorsys 
  2. import PIL.Image as Image 
  3. def get_dominant_color(image): 
  4.     max_score = 0.0001 
  5.     dominant_color = None 
  6.     for count,(r,g,b) in image.getcolors(image.size[0]*image.size[1]): 
  7.         # 转为HSV标准 
  8.         saturation = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)[1] 
  9.         y = min(abs(r*2104+g*4130+b*802+4096+131072)>>13,235) 
  10.         y = (y-16.0)/(235-16) 
  11.         #忽略高亮色 
  12.         if y > 0.9: 
  13.             continue 
  14.         score = (saturation+0.1)*count 
  15.         if score > max_score: 
  16.             max_score = score 
  17.             dominant_color = (r,g,b) 
  18.     return dominant_color 

为了减少误差,需要裁剪多个不同位置的图片,保存在本地的一个文件夹中,读取文件,提取颜色,求平均值,得到的番茄最终的 RGB 颜色,代码如下:



  1. import os 
  2. import getcolor 
  3. from os.path import join as pjoin 
  4. from scipy import misc 
  5. def load_color(color_dir,list):  
  6.     count = 0 
  7.     for dir in os.listdir(color_dir):   
  8.         img_dir = pjoin(color_dir, dir)   
  9.         image = getcolor.Image.open(img_dir) 
  10.         image = image.convert('RGB') 
  11.         get=getcolor.get_dominant_color(image) 
  12.         list.append(get) 
  13.         count = count+1 
  14.         #print(person_dir) 
  15.     #print(count) 
  16.     return count 
  17. def Mean_color(count,list): 
  18.      Mean_R=Mean_G=Mean_B=0 
  19.      for i in range(count): 
  20.         tuple=list[i] 
  21.         Mean_R+=tuple[0] 
  22.         Mean_G+=tuple[1] 
  23.         Mean_B+=tuple[2] 
  24.      MeanC=((int)(Mean_R/count),(int)(Mean_G/count),(int)(Mean_B/count)) 
  25.      return Me 

番茄的颜色提取到了,那么和什么做比对呢?

当然是口红的数据,文摘菌这儿用到了 5 个品牌,分别是圣罗兰、香奈儿可可小姐、迪奥、美宝莲、纪梵希,共 17 个系列,271 个口红色号。

数据集是一个嵌套的字典数据结构,存为 json 串的形式,里面记录了每个口红品牌系列下不同口红色号的颜色 id、名称、和 16 进制颜色值。

lipstick.json部分数据集展示如下:



  1. {"brands":[{"name":"圣罗兰","series": 
  2. [{"name":"莹亮纯魅唇膏","lipsticks": 
  3. [{"color":"#D62352","id":"49","name":"撩骚"}, 
  4. {"color":"#DC4B41","id":"14","name":"一见倾心"}, 
  5. {"color":"#B22146","id":"05","name":"浮生若梦"}, 

数据集中存储的 RGB 颜色是 16 进制的字符串形式,需要将其转换成 RGB 值,比较两个颜色相近与否。

实际上是比较 RGB 三个分量维度上的误差,最小的口红输出对应的品牌、系列、色号和 id。

代码如下:



  1. import json 
  2. import getcolor 
  3. import numpy as np 
  4. import lipcolor 
  5. #filename = 'temp.txt' 
  6. ##write the temp data to file## 
  7. def WtoFile(filename,RGB_temp): 
  8.     num=len(RGB_temp) 
  9.     with open(filename,'w') as f:  
  10.        for i in range(num): 
  11.            s = str(RGB_temp[i]).replace('[','').replace(']','') 
  12.            f.write(s) 
  13.            f.write("\n") 
  14. #operate the data # 
  15. ##save the brand&series&color id&color name to sum_list## 
  16. ##covert the color #D62352 to RGB_array## 
  17. ##caculate the RGB difference to RGB_temp and write the value to file## 
  18. def data_operate(): 
  19.     with open('lipstick.json', 'r', encoding='utf-8') as f: 
  20.       ret_dic = json.load(f) 
  21.       #print(ret_dic['brands']) 
  22.       #print(type(ret_dic)) # <class 'dict'> 
  23.       #print(ret_dic['brands'][0]['name'])  
  24.       b_num=len(ret_dic['brands']) 
  25.       #print(b_num)#brands number 
  26.       s_list=[] 
  27.       #series brands# 
  28.       for i in range(len(ret_dic['brands'])): 
  29.           s_num=len(ret_dic['brands'][i]['series']) 
  30.           s_list.append(s_num) 
  31.           #print("{0} has {1} series".format((ret_dic['brands'][i]['name']),(s_list[i]))) 
  32.       #the lipstick color of every brands every series# 
  33.       #the first loop calculate the total color numbers 
  34.       sum=0 
  35.       for b1 in range(b_num): 
  36.           for s1 in range(s_list[b1]): 
  37.               brand_name=ret_dic['brands'][b1]['name'] 
  38.               lip_name=ret_dic['brands'][b1]['series'][s1]['name'] 
  39.               color_num=len(ret_dic['brands'][b1]['series'][s1]['lipsticks']) 
  40.               sum+=color_num#calculate the total color numbers 
  41.       #the second loop save the message to a list# 
  42.       sum_list=np.zeros((sum,4), dtype=(str,8)) 
  43.       value_array=np.zeros((sum,6), dtype=int) 
  44.       for b2 in range(b_num): 
  45.           for s2 in range(s_list[b2]): 
  46.               brand_name=ret_dic['brands'][b2]['name'] 
  47.               #print(type(brand_name)) 
  48.               lip_name=ret_dic['brands'][b2]['series'][s2]['name'] 
  49.               color_num=len(ret_dic['brands'][b2]['series'][s2]['lipsticks']) 
  50.               for c in range(color_num): 
  51.                     color_value=ret_dic['brands'][b2]['series'][s2]['lipsticks'][c]['color'] 
  52.                     color_name=ret_dic['brands'][b2]['series'][s2]['lipsticks'][c]['name'] 
  53.                     color_id=ret_dic['brands'][b2]['series'][s2]['lipsticks'][c]['id'] 
  54.                     #print("{0} series {1} has {2} colors,color {3}:{4}".format(brand_name,lip_name,color_num,c+1,color_name)) 
  55.                     sum_list[i][0]=brand_name 
  56.                     sum_list[i][1]=lip_name 
  57.                     sum_list[i][2]=color_id 
  58.                     sum_list[i][3]=color_name 
  59.                     #value_array[i]=value_array[i][1] 
  60.                     #convert "#D62352" to [13  6  2  3  5  2]# 
  61.                     for l in range(6): 
  62.                         temp=color_value[l+1] 
  63.                         if(temp>='A'and temp<='F'): 
  64.                            temp1=ord(temp)-ord('A')+10 
  65.                         else: 
  66.                            temp1=ord(temp)-ord('0') 
  67.                         value_array[i][l]=temp1 
  68.     #the third loop covert value_array to RGB_array# 
  69.       RGB_array=np.zeros((sum,3), dtype=int) 
  70.       for i in range(sum): 
  71.           RGB_array[i][0]=value_array[i][0]*16+value_array[i][1] 
  72.           RGB_array[i][1]=value_array[i][2]*16+value_array[i][3] 
  73.           RGB_array[i][2]=value_array[i][4]*16+value_array[i][5] 
  74.       #calculate the similar and save to RGB_temp 
  75.       #RGB_temp=np.zeros((sum,1), dtype=int) 
  76.       RGB_temp=np.zeros((sum,1), dtype=float) 
  77.       for i in range(sum): 
  78.           R=RGB_array[i][0] 
  79.           G=RGB_array[i][1] 
  80.           B=RGB_array[i][2] 
  81.           RGB_temp[i]=abs(get[0]-R)+abs(get[1]*3/4-G)+abs(get[2]-B) 
  82.       RGB_temp.tolist();#covert array to list 
  83.       #print(RGB_temp) 
  84.       filename="temp.txt" 
  85.       WtoFile(filename,RGB_temp) 
  86.       #sort the RGB_temp# 
  87.       result=sorted(range(len(RGB_temp)), key=lambda k: RGB_temp[k]) 
  88.       #print(result) 
  89.       #output the three max prob of the lipsticks# 
  90.       print("The first three possible lipstick brand and color id&name are as follows:") 
  91.       for i in range(3): 
  92.           idex=result[i] 
  93.           print(sum_list[idex]) 
  94.       print("The first three possible lipstick brand RGB value are as follows:") 
  95.       for i in range(3): 
  96.           idex=result[i] 
  97.           R=RGB_array[idex][0] 
  98.           G=RGB_array[idex][1] 
  99.           B=RGB_array[idex][2] 
  100.           tuple=(R,G,B) 
  101.           print(tuple) 
  102. if __name__ == '__main__': 
  103.      #image = getcolor.Image.open(inputpath) 
  104.      #image = image.convert('RGB') 
  105.      #get=getcolor.get_dominant_color(image)#tuple #get=(231, 213, 211) 
  106.      list=[] 
  107.      color_dir="output" 
  108.      count=lipcolor.load_color(color_dir,list) 
  109.      get=lipcolor.Mean_color(count,list) 
  110.      print("the extracted RGB value of the color is {0}".format(get)) 
  111.      #operate the data# 
  112.      data_operat 

输出最有可能吻合番茄颜色的前三个口红的信息,然后在 Spyder 中的运行结果:

89335a3790f8c6c4dacd79801f9b2bd4.jpg-wh_600x-s_3302761722.jpg

可以看到最有可能的三个口红品牌色号的 RGB 值与番茄的 RGB 值是非常接近的。

提取到的番茄颜色:

'迪奥' '烈艳蓝金唇膏' '080' '微笑正红’的颜色:

'圣罗兰' '纯口红' '56' '橙红织锦'的颜色:

'纪梵希' '高定香榭天鹅绒唇' '325' '圣水红'的颜色:

我已经眼花缭乱,三个颜色……有区别吗?!以后不如准备统一叫它们,番茄色!

1b7a6ff80e3b0b19e9fb45924bc0c4a2.jpg

不过,这也正说明了,刚刚的提取&对比方法可行!

既然可以识别番茄的颜色,那么,可以识别人像中的口红色号吗?

进入正题!人像口红色号识别

接下来,我们需要做的是输入一张人像图片,可以自动识别其中的嘴唇区域,并提取出嘴唇区域中的一部分做为颜色提取的源图像。

这里就要用到 CV 的人脸识别了,还好 Dlib 库又帮助我们减轻一大部分的工作量。

Dlib 中有自带的 68 个人脸的识别器,可以得到人脸部位包括眉毛、眼睛、鼻梁、面部轮廓和嘴唇区域的具体点的位置,到这儿,我以为很轻松就可以截到嘴唇区域了,结果有点尴尬.........

我们首先找到了一张小姐姐的照片:

73d1ae3aea709f1e692235d879c51d18.jpg

截取到的嘴唇区域如下:

很明显的看到上下嘴唇黑色的区域也截取到了,这对后续的提色有影响,所以不得不回到最初的 68 个检测点来思考人生。

dfab4f39dce5914dd6b878199f40336c.jpg

圣罗兰官网 #842C71 口红

标记的 68 个人脸检测点如上图所示,而嘴唇部位是从第 49 个标记点开始的(数组的话,下标是 48)。

为了尽可能的截取到均匀成色的嘴唇片段,刚开始是想从第 50 个标记点对角线截取到第 56 个标记点,而这不可避免的会截取到上下嘴唇之间的缝隙,这儿的阴影也会影响后续的颜色提取准确度。

考虑到下嘴唇比上嘴唇宽,所以截取到下嘴唇中间的两个小正方形区域:

人脸识别和截取嘴唇区域的代码如下:



  1. import numpy as np  
  2. import cv2 
  3. import dlib 
  4. from PIL import Image 
  5. def crop(source,pos): 
  6.       x1=pos[2][0] 
  7.       y1=pos[2][1] 
  8.       x2=pos[1][0] 
  9.       y2=pos[1][1] 
  10.       d=abs(x2-x1) 
  11.       region = source[(int)(y1-d*0.75):y2,x1:x2] 
  12.       # save the image 
  13.       cv2.imwrite("output/Mouth1.jpg", region) 
  14.       x1=pos[1][0] 
  15.       y1=pos[1][1] 
  16.       x2=pos[0][0] 
  17.       y2=pos[0][1] 
  18.       d=abs(x1-x2) 
  19.       region = source[y1-d:y2,x1:x2] 
  20.       # save the image 
  21.       cv2.imwrite("output/Mouth2.jpg", region) 
  22. def detect_mouth(img,pos): 
  23.         gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
  24.         gray = cv2.equalizeHist(gray) 
  25.         detector = dlib.get_frontal_face_detector() 
  26.         #use the predictor  
  27.         predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') 
  28.         dets = detector(img, 1)    
  29.         print("Number of faces detected: {}".format(len(dets))) 
  30.         for a in dets:     
  31.            cv2.rectangle(img,(a.left(),a.top()),(a.right(),a.bottom()),(255,0,0)) 
  32.         #point_list=[]#save the mouth point to point_list[]# 
  33.         #Extract 68 feature points of the face and crop the lip image# 
  34.         for index, face in enumerate(dets): 
  35.            print('face {}; left {}; top {}; right {}; bottom {}'.format(index, face.left(), face.top(), face.right(), face.bottom())) 
  36.            shape = predictor(gray, face) 
  37.            for i, pt in enumerate(shape.parts()): 
  38.             #print('Part {}: {}'.format(i, pt)) 
  39.             #print(i) 
  40.              pt_pos = (pt.x, pt.y) 
  41.              if i>=48 and i<=67: 
  42.                 cv2.circle(img, pt_pos, 2, (255, 0, 0), 1) 
  43.              if i>=56 and i<=58: 
  44.                 #print(pt_pos) 
  45.                 pos[i-56][0]=pt.x 
  46.                 pos[i-56][1]=pt.y 
  47.              #cv2.circle(img, pt_pos, 2, (255, 0, 0), 1) 
  48.         return img 
  49. if __name__ == "__main__":  
  50.       img = cv2.imread("test3.png") 
  51.       #copy the input image for the later crop# 
  52.       img_clone = np.copy(img) 
  53.       cv2.imwrite("input/source.jpg",img_clone) 
  54.       #save the lip position to pos array# 
  55.       pos=np.zeros((3,2), dtype=int) 
  56.       result=detect_mouth(img,pos) 
  57.       cv2.imwrite("input/source2.jpg",result) 
  58.       #crop the lip areas# 
  59.       source = cv2.imread("input/source.jpg") 
  60.       crop(source,pos) 
  61.       # show the result 
  62.       cv2.imshow('FaceDetect',result) 
  63.       cv2.waitKey(0)  
  64.       cv2.destroyAllWindow 

既然已经截取到嘴唇的小矩形图像了,接下来的工作就和前面一样了,在数据库中对比每个 RGB 值输出最小误差对应的口红信息,而这儿也有难到我。

单纯的比对 RGB 分量对口红色号来说并不适用,有可能每个分量相差很小,而叠加起来的颜色和提取到的颜色并不相似,在颜色的比对上需要手动调参。

几经波折,最后输出的结果还是可以接受的,上图人像中涂的口红色号,感兴趣的读者可以查下正好是下面输出排名第一的口红信息。

48c50c9b04d9fe80f5b689e877de489f.jpg-wh_600x-s_491111299.jpg

误差分析

e00e8ab033a3a1ba71c083c3eae6482b.jpg

对于我们测试的图片信息,标记了嘴唇区域的特征点,我们提取到的 RGB 值(156,59,103)颜色如下所示:

可以看到和图片的颜色已经十分接近了,而数据集合 lipstick.json 中这种口红存储的 16 进制颜色值为 #842C71,对应的颜色如下:

明显看到数据集存储的颜色和实际照片的颜色是有些许误差的,而在本文算法实现过程中,又不可避免的有以下误差:

  • 嘴唇区域截取不可避免会截取到皮肤中的一部分颜色,虽然算法已经将那种可能降到最低。
  • 颜色提取上,虽然截取多个嘴唇图片求平均值,但是本身的提取算法还是和实际值稍有偏差。
  • RGB 颜色相似度比对的算法也不够精确。
  • 最最重要的是,照片必须是原图,而且光线要自然,加了滤镜的图是怎么也不可能识别出来的。

以上种种,使得让计算机快速高效地识别不同的口红色号还是有困难的,原来计算机有时候也会很直男。

实时人像口红色号预测

看到这儿,可能很多读者朋友想实时地试一下能不能让计算机判断自己的口红色号,这对于 OpenCV 这一强大的图形操作库来说,不是什么问题。

它可以打开你的摄像头,读取每一帧的图片,结合前文提到的人脸识别代码,可以实时地截取到嘴唇区域的图片,然后交给计算机预测,从此再也不怕女朋友的灵魂拷问!

de438e90989b784ab9b9092aa3c6d15d.gif

最后,附上打开摄像头的代码,快叫女朋友过来试下吧!



  1. #coding=utf8 
  2. import cv2 
  3. import time 
  4. print('Press Esc to exit') 
  5. imgWindow = cv2.namedWindow('FaceDetect', cv2.WINDOW_NORMAL) 
  6. import sys 
  7. import os 
  8. import dlib 
  9. import glob 
  10. import numpy 
  11. from skimage import io 
  12. def detect_face(): 
  13.     capInput = cv2.VideoCapture(0) 
  14.     #nextCaptureTime = time.time() 
  15.     faces = [] 
  16.     feas = []  
  17.     if not capInput.isOpened(): print('Capture failed because of camera') 
  18.     while 1: 
  19.         ret, img = capInput.read() 
  20.         gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
  21.         gray = cv2.equalizeHist(gray) 
  22.         time=0 
  23.         eTime = time.time() + 0.1 
  24.         detector = dlib.get_frontal_face_detector()  
  25.         predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') 
  26.         dets = detector(gray, 1)   
  27.         print("Number of faces detected: {}".format(len(dets))) 
  28.         for a in dets:     
  29.            cv2.rectangle(img,(a.left(),a.top()),(a.right(),a.bottom()),(255,0,0)) 
  30.         for index, face in enumerate(dets): 
  31.            print('face {}; left {}; top {}; right {}; bottom {}'.format(index, face.left(), face.top(), face.right(), face.bottom())) 
  32.            shape = predictor(gray, face)    
  33.            for i, pt in enumerate(shape.parts()): 
  34.             #print('Part {}: {}'.format(i, pt)) 
  35.              pt_pos = (pt.x, pt.y) 
  36.              cv2.circle(img, pt_pos, 2, (255, 0, 0), 1) 
  37.         cv2.imshow('FaceDetect',img) 
  38.         if cv2.waitKey(1) & 0xFF == 27: break 
  39.     capInput.release() 
  40.     cv2.destroyAllWindows() 
  41. if __name__ == "__main__":  
  42.     detect_face() 

好啦,佳期如梦,双星良夜,在一个充满爱意的日子里,定位好女神常用的口红色号,和那个她来场华丽的邂逅吧!

57cec62fdf9e12b87248ee20e26cbd3d.jpg-wh_600x-s_2421293893.jpg

来给大家送一波福利,包邮送 6 本 Python 技术书籍,参与方式很简单,关注51CTO技术栈公众号,在公众号后台回复「抽奖」,弹出小程序后点击参与。

开奖时间是 9 月 25 日 20:00 ,一定要留意微信消息,如果你中奖了就尽快微信联系我,告诉我想要的书和快递信息。一天之内没有回复,送书名额就转给其他人了。

06b2a54c97a0c09401603bab7aea68d4.gif-wh_600x-s_2946624692.gif

【编辑推荐】

【责任编辑:武晓燕 TEL:(010)68476606】

点赞 5


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK