前言
本項目利用了Dlib中已經(jīng)成熟的68點人臉特征點檢測功能,并結(jié)合了Python庫"face_recognition",以便進行口紅顏色的匹配和推薦。
首先,使用Dlib的人臉特征點檢測功能,我們可以精確地定位人臉上的68個關(guān)鍵點,包括眼睛、嘴巴、鼻子等部位。這些關(guān)鍵點的檢測能力使我們能夠準確地識別嘴唇的位置和形狀。
接下來,我們使用"face_recognition"庫來處理這些檢測到的區(qū)域。具體而言,我們關(guān)注嘴唇區(qū)域并提取其顏色信息。這可能涉及到將嘴唇區(qū)域的像素值轉(zhuǎn)化為顏色的特征,比如RGB值或者HSV值。
一旦我們獲得了嘴唇的顏色信息,接下來的步驟就是尋找與這種顏色最相近的口紅顏色。這可以涉及到一個顏色匹配算法,例如計算顏色之間的歐幾里德距離或色彩空間的相似度。
最后,根據(jù)顏色匹配的結(jié)果,我們可以輸出口紅推薦信息,包括口紅的品牌、色號和購買鏈接等。這樣,用戶可以根據(jù)他們的嘴唇顏色找到最適合的口紅。
本項目結(jié)合計算機視覺和顏色匹配技術(shù),為用戶提供了一種便捷的方式來選擇合適的口紅顏色,以匹配他們的嘴唇顏色和個人喜好。這對于化妝愛好者和購物者來說都具有實際的應(yīng)用價值。
總體設(shè)計
本部分包括系統(tǒng)整體結(jié)構(gòu)圖和系統(tǒng)流程圖。
系統(tǒng)整體結(jié)構(gòu)圖
系統(tǒng)整體結(jié)構(gòu)如圖所示。
系統(tǒng)流程圖
正則匹配系統(tǒng)流程如圖所示。
保存信息系統(tǒng)流程如圖所示。
色彩空間轉(zhuǎn)換流程如圖所示。
尋找相應(yīng)顏色模塊如圖所示。
運行環(huán)境
本部分包括Python環(huán)境、TensorFlow環(huán)境、安裝face_recognitio、colorsys模塊、PyQt5、QCandyUi、庫依賴關(guān)系。
Python環(huán)境
需要Python 3.6及以上配置,在Windows環(huán)境下推薦下載Anaconda完成Python所需環(huán)境的配置,下載地址為https://www.anaconda.com/,也可下載虛擬機在Linux環(huán)境下運行代碼。
TensorFlow環(huán)境
打開Anaconda Prompt,輸入清華倉庫鏡像:
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/conda config --set show_channel_urls yes
創(chuàng)建Python 3.6的環(huán)境,名稱為TensorFlow,此時Python版本和后面TensorFlow的版本有匹配問題,此步選擇Python 3.6。
conda create -n tensorflow Python=3.6
有需要確認的地方,都輸入y。
在Anaconda Prompt中激活TensorFlow環(huán)境:
activate tensorflow
安裝CPU版本的TensorFlow:
pip install tensorflow
安裝完畢。
安裝face_ recognition
在Windows 10下安裝face_recognition第三方庫:
①在Anaconda的Python 3.6版本命令提示符下輸入pip install CMake
命令安裝CMake;
②安裝Dlib。經(jīng)查詢發(fā)現(xiàn)face_recognition第三方庫與Dlib的19.7.0版本相匹配,所以安裝Dlib時要使用以下命令: pip install dlib==19.7.0
,在DOS命令行輸入pip install face_recognition
命令安裝face_recognition第三方庫。
安裝colorsys模塊
colorsys模塊用于RGB和YIQ/HLS/HSV顏色模式雙向轉(zhuǎn)換接口。提供6個函數(shù),其中3個用于RGB轉(zhuǎn)YIQ/HLS/HSV,另外3個將YIQ/HLS/HSV轉(zhuǎn)RGB。
PIL庫可以完成圖像歸檔和圖像處理兩方面的需求。圖像歸檔:對圖像進行批處理、生成圖像預覽、圖像格式轉(zhuǎn)換等;圖像處理:基本處理、像素處理、顏色處理等。Image是PIL中最重要的模塊,有一個類叫作Image,與模塊名稱相同。Image類有很多函數(shù)、方法及屬性。
安裝PyQt 5
安裝步驟:打開CMD,輸入conda activate tensorflow
命令;
pip install pyqt5
需要注意,conda庫中沒有PyQt5。
在網(wǎng)絡(luò)質(zhì)量不佳時有可能安裝失敗,可以使用下載*.whl文件并用pip install wheel
的方式進行PyQt 5的安裝部署;
pip install pyqt5-tools
安裝后關(guān)閉CMD,到達文件安裝位置尋找designer.exe
;
打開designer.exe
即可使用該工具迅速畫出樣式并得到*ui
文件;
打開CMD,跳轉(zhuǎn)到對應(yīng)位置。使用pyuic工具將*ui
文件轉(zhuǎn)換為ui_*.py
文件;
打開ui_*py
文件寫入signal and slot相關(guān)內(nèi)容,確定繼承關(guān)系。
安裝QCandyUi
使用conda activate tensorflow
命令激活環(huán)境后,使用pip install QCandyUi
命令安裝即可。
庫依賴關(guān)系
庫依賴如表所示。
模塊實現(xiàn)
本項目包括數(shù)據(jù)預處理和系統(tǒng)搭建2個模塊。下面分別給出各模塊的功能介紹及相關(guān)代碼。
1. 數(shù)據(jù)預處理
本部分包括源數(shù)據(jù)的存儲、數(shù)據(jù)處理和數(shù)據(jù)合并。
1)源數(shù)據(jù)的存儲
數(shù)據(jù)下載地址為https://www.kaggle.com/c/facial-keypoints-detection/data,存儲形式如圖所示。
2)處理數(shù)據(jù)
本部分代碼因需要處理多個品牌,代碼結(jié)構(gòu)相似,存在重復現(xiàn)象,本處以口紅品牌M.A.C為例展示處理方法,相關(guān)代碼如下:
#-*- coding: utf-8 -*-
import json
import re
import os
path="D:/homework/大三下信息系統(tǒng)設(shè)計/lipsticks/"
brand="mac/"
brandpathli=[]
dict_Brand={"name":brand[:-1],"series":None}
dict_series={"name":None,"lipsticks":None}
dict_name={"color":"#ffffff", "id":"-1", "name":"none"}
#預設(shè)參數(shù),在處理不同品牌時,只需要改變brand和path中的內(nèi)容即可
def par_mac(str):
#對該口紅的品牌、顏色、色號進行匹配
dict_name={"color":"#ffffff", "id":"-1", "name":"none"}
#設(shè)定默認值,當發(fā)現(xiàn)顏色是黑色或ID=-1可及時丟棄不合法的列表
matchObj_color = re.search( r'#\w{6}', str, re.M|re.I)
if (matchObj_color!=None):
dict_name["color"]=matchObj_color.group().upper()
#print (matchObj_color.group())調(diào)試代碼
matchObj_id = re.search( r"\">\d{3}" , str, re.M|re.I)
if (matchObj_id!=None):
dict_name["id"]=matchObj_id.group()[2:]
#print (matchObj_id.group()[2:])調(diào)試代碼
matchObj_name = re.search( r">\d{0,}[ ]?([A-Z][a-z]*[,]?[ ]?[!?]?){1,}" , str, re.M|re.I)
if (matchObj_name!=None):
dict_name["name"]=matchObj_name.group()[1:]
return dict_name
#查找文件夾內(nèi)所有文件的名稱
def eachFile(filepath):
pathDir = os.listdir(filepath)
for allDir in pathDir:
child = os.path.join('%s%s' % (filepath, allDir))
print("children",child)#即該目錄下所有文件的名字
brandpathli.append(child)
#讀取文件路徑名對應(yīng)的內(nèi)容
def readFile(filename):
fopen = open(filename, 'r') #r 代表read
list_series=[]#文件中每一行的內(nèi)容
for eachLine in fopen:
#print( "讀取到得內(nèi)容如下:",eachLine)調(diào)試代碼
dict_name=par_mac(eachLine)
if(dict_name["color"]=="#ffffff"):
continue
list_series.append(dict_name)
fopen.close()
return list_series#返回每個系列的所有口紅
if __name__ == '__main__':
#filePath = path+brand+subpath調(diào)試代碼,可以通過不同方式訪問數(shù)據(jù)
filePathC = path+brand
eachFile(filePathC)
list_brand=[]
for i in brandpathli:
dict_series={"name":None,"lipsticks":None}
list_series=readFile(i) #每個系列的所有口紅
#print(dict_name)調(diào)試代碼
brandname=i.split('/')[-1].split('.')[0]
#print("mainpring",brandname)調(diào)試代碼
dict_series["name"]=brandname
dict_series["lipsticks"]=list_series
#獲得{系列名,口紅色號}字典
list_brand.append(dict_series)
print("dict_series",list_brand)
dict_Brand["series"]=list_brand
#dict_Brand["brands"][1]["series"]調(diào)試代碼
file = open('D:/homework/大三下信息系統(tǒng)設(shè)計/json/'+brand.split('/')[0]+'.json','w',encoding='utf-8')
#在遇到長文本時需要處理編碼格式以保證存入的數(shù)據(jù)不是亂碼
json = json.dump(dict_Brand,file)
print(json)
file.close()
3)合并得到j(luò)son文件
合并得到j(luò)son文件即可組成口紅色號數(shù)據(jù)庫,如圖所示。
2. 系統(tǒng)搭建
本部分包括人臉識別,提取唇部輪廓并創(chuàng)建蒙版,劃分嘴唇區(qū)域,提取圖片顏色,獲取色號庫,比較并得出結(jié)果,創(chuàng)建圖形化界面等。
1)人臉識別
在識別唇部之前,定位到人臉,用face_recognition
對圖片中的人臉進行識別。
import face_recognition
path="*.jpg"
#放入一張照片
image = face_recognition.load_image_file(path)
#找到圖片中所有人臉
print(type(image))
face_locations = face_recognition.face_locations(image)
print(face_locations)
#或者在圖像中找到面部特征(還可以通過len(face_locations)得到圖片中的人臉數(shù)
face_landmarks_list = face_recognition.face_landmarks(image)
print(face_landmarks_list)
#為圖像中的每個人臉獲取face_encodings
list_of_face_encodings = face_recognition.face_encodings(image)
2)提取唇部輪廓并創(chuàng)建蒙版
為方便提取唇部顏色,將識別到的上下嘴唇及輪廓用白色填充,得到一張黑底唇部留白的蒙版。
pil_image = Image.fromarray(image)
a=pil_image.size
#改變類型
print(a,type(a))
blank_mouse = Image.new('RGB', (a[0],a[1]), (0, 0, 0))
#新建一張黑色圖片
for face_landmarks in face_landmarks_list:
d = ImageDraw.Draw(blank_mouse, 'RGBA')
#把嘴唇涂白
d.polygon(face_landmarks['top_lip'], fill=(255,255,255,255))
d.polygon(face_landmarks['bottom_lip'], fill=(255, 255,255, 255))
d.line(face_landmarks['top_lip'], fill=(255, 255,255, 255), width=8)
blank_mouse.show()
#展示
blank_mouse=blank_mouse.crop((pos[3], pos[0], pos[1], pos[2]))
#(left, upper, right, lower) 修剪面部區(qū)域
Image._show(blank_mouse)
3)劃分嘴唇區(qū)域
進一步對圖像進行處理,在原圖像中保留唇部區(qū)域,即上步中留白區(qū)域,非唇部區(qū)域用黑色覆蓋,便于后續(xù)提取顏色。
def masklayer(origin,mask):
#創(chuàng)建函數(shù),origin和mask均為Image函數(shù)對應(yīng)的圖片格式,將其轉(zhuǎn)換為數(shù)組,再操作
mask1=np.array(mask)
print(mask1.shape)
origin1=np.array(origin)
print(origin1.shape)
for i in range(len(mask1)):
for j in range(len(mask1[i])):
#如果mask在這個區(qū)域是黑色的,則程序不需要這部分圖片內(nèi)容設(shè)定原圖中該區(qū)域rgb=000
if (mask1[i][j][1]>=128):#保留嘴唇區(qū)域
pass
else:#其他區(qū)域變?yōu)楹谏?/span>
origin1[i][j]=[0,0,0]
new_png = Image.fromarray(origin1)
new_png.show()
#new_png.save('testpic.JPG')
return new_png
#調(diào)用編寫的函數(shù),將嘴唇區(qū)域框選出來
cropped=masklayer(cropped_face,blank_mouse)
經(jīng)過以上步驟,可以獲取唇部區(qū)域并打印,如圖所示。
4)提取圖片顏色
顏色空間可以分為基色顏色空間和色、亮分離顏色空間兩類。前者是RGB,后者包括YUV和HSV等。在RGB顏色空間中,任意色光F都可以用R、G、B三基色不同分量的相加混合而成:F=r[R]+r[G]+r[B]。 RGB色彩空間還可以用一個三維的立方體來描述,當三基色分量都為0 (最弱)時混合為黑色光;當三基色都為定值( 最大值由存儲空間決定)時混合為白色光。
HSV顏色空間用下圖描述。正對著的面為S=100%,Z軸為V值正方向,從左至右為H間隔60°展開。程序采用了《廣告圖片生成方法、裝置以及存儲介質(zhì)》中的部分思想。
import colorsys
import PIL.Image as Image
def get_dominant_color(image):
#顏色模式轉(zhuǎn)換,以便輸出RGB顏色值
image = image.convert('RGB')
#生成縮略圖,減少計算量,減小cpu壓力,縮短運算時間
image.thumbnail((200, 200))
max_score =0
dominant_color = 0
for count,(r,g,b) in image.getcolors(image.size[0]*image.size[1]):
#忽略黑色背景
if (r<100) :
continue
#轉(zhuǎn)換為HSV獲取顏色飽和度,范圍(0,1)
saturation = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)[1]
#轉(zhuǎn)換為YUV計算亮度
y = min(abs(r*2104+g*4130+b*802+4096+131072)>>13,235)
#將亮度從(16,235)縮放到(0,1)
y = (y-16.0)/(235-16)
#忽略高亮色
if y > 0.9:
continue
#選擇飽和度高的顏色
#將飽和度加0.1,這樣就不會通過將計數(shù)乘以0來完全忽略灰度顏色,但給它們較低的權(quán)重
score = (saturation+0.1)*count
if score > max_score:
max_score = score
dominant_color = (r,g,b)
return dominant_color
5)獲取色號庫
對色號庫進行操作,計算共有多少種顏色,并根據(jù)計算結(jié)果將json文件中的數(shù)據(jù)存為數(shù)組,轉(zhuǎn)換為list方便操作。
def RGBhex_2RGB(rgb_hex):
#print(rgb_hex) 調(diào)試代碼
RGB=[0,0,0]
temp_num=0
for i in range(len(rgb_hex)):
temp_num=0
temp=rgb_hex[i]
if(i!=0):
#將字母轉(zhuǎn)換為ASCII表中位置
if(temp>='A'and temp<='F'):
temp_num=ord(temp)-55
#將ABCDEF轉(zhuǎn)換為10~15間的數(shù)字
else:
#將字符數(shù)字轉(zhuǎn)換為0~9間的數(shù)字
temp_num=ord(temp)-48
if(i%2==1):
#根據(jù)位置乘進制
RGB[int((i/2)-0.5)]=RGB[int((i/2)-0.5)]+16*temp_num
else:
RGB[int((i/2)-0.5)]=RGB[int((i/2)-0.5)]+temp_num
#print(RGB)調(diào)試代碼
return RGB
import numpy as np
import json
#對色號庫進行操作
#將品牌、系列顏色ID和顏色名稱保存到匯總列表中
def operate(target_color):
sum_all=0
with open('lipstick.json', 'r', encoding='utf-8') as f:
js2dic = json.load(f)
#讀取json
brands_n=len(js2dic['brands'])
print(brands_n)
series_n=0
for brands_i in range(brands_n):
series_n=len(js2dic['brands'][brands_i]['series'])
print("{0} has {1} series".format((js2dic['brands'][brands_i]['name']),series_n))
for series_i in range(series_n):
brand_name=js2dic['brands'][brands_i]['name']
lip_name=js2dic['brands'][brands_i]['series'][series_i]['name']
color_num=len(js2dic['brands'][brands_i]['series'][series_i]['lipsticks'])
sum_all=color_num+sum_all
#計算顏色總數(shù)
print(sum_all)
catalog=np.zeros((sum_all,4), dtype=(str,20))
catalog_color=np.zeros((sum_all,3), dtype=int)
#根據(jù)顏色數(shù)分配空間
rank_color=np.zeros((sum_all,1),dtype=int)
6)比較并得出結(jié)果
提取出的顏色與庫中顏色比較,得到誤差最小的三組數(shù)據(jù)。將每個色號在R、G、B三個分量的數(shù)值與提取出的顏色RGB值分別做差并求和(權(quán)重自定),作為兩個顏色的相似度。
#catalog分為四部分:品牌名稱、唇膏名稱、色號ID、色號值
#將信息存入表格,這個循環(huán)可以將信息存入Python程序建立數(shù)組中
sum_i=0
for brands_i in range(brands_n):
series_n=len(js2dic['brands'][brands_i]['series'])
#print("brand_name",js2dic['brands'][brands_i]['name'])
catalog[sum_i][0]=js2dic['brands'][brands_i]['name']
for series_i in range(series_n): color_num=len(js2dic['brands'][brands_i]['series'][series_i]['lipsticks'])
for color_i in range(color_num):
catalog[sum_i][0]=js2dic['brands'][brands_i]['name'] catalog[sum_i][1]=js2dic['brands'][brands_i]['series'][series_i]['name'] catalog[sum_i][2]=js2dic['brands'][brands_i]['series'][series_i]['lipsticks'][color_i]['name'] catalog[sum_i][3]=js2dic['brands'][brands_i]['series'][series_i]['lipsticks'][color_i]['id'] catalog_color[sum_i]=RGBhex_2RGB(js2dic['brands'][brands_i]['series'][series_i]['lipsticks'][color_i]['color'])
sum_i+=1
#print(sum_i)調(diào)試代碼
print(catalog.shape)
RGB_distance=np.zeros((sum_all,1), dtype=float)
for i in range(sum_all):
#計算相似度,target是此前通過domain得到的值
RGB_distance[i]=abs(target_color[0]-catalog_color[i][0])+abs((target_color[1]-catalog_color[i][1])*(1/5))+abs(target_color[2]-catalog_color[i][2])
RGB_distance.tolist()
result=sorted(range(len(RGB_distance)), key=lambda k: RGB_distance[k])
#獲得顏色最像的三只口紅(以顏色的相近度為規(guī)則排序,返回位置數(shù)據(jù))
print("顏色最像的三只口紅及其顏色")
result_show=[]
for i in range(3):
loc=result[i]
color_show=tuple(catalog_color[loc])
print("catalog index",catalog[loc],color_show)
#operate([155, 44, 69]) 調(diào)試代碼
if __name__ == '__main__':
get=get_dominant_color(cropped)
print("獲得的口紅顏色{0}".format(get))
#計算相似度,get是此前通過domain得到的值
operate(get)
7)創(chuàng)建圖形化界面
使用designer工具創(chuàng)建GUI文件,并使用pyuic工具進行ui到.py
文件的轉(zhuǎn)換。對該*.py
文件不建議直接修改,一般使用import其他文件定義操作類的方法進行信號和槽的鏈接。
#-*- coding: utf-8 -*-
#從讀取ui文件“myuidesign.ui”生成的窗體實現(xiàn)
#創(chuàng)建人:PyQt5 UI代碼生成器5.10
#警告!此文件中做的所有更改都將丟失
from PyQt5 import QtCore, QtGUI, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QWidget,QGraphicsScene
from PyQt5.QtCore import QFileInfo
from detectface import my_face_recognition
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGUI.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtWidgets.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtWidgets.QApplication.translate(context, text, disambig)
#以上代碼處理了文字的編碼格式
#建立UI函數(shù)
class Ui_Dialog(object):
def __init__(self):
super(Ui_Dialog, self).__init__()
self.imgPath=""
self.face_recognize_object =None
self.showFullImage = True
self.brand=[]
self.color=[]
def setupUi(self, Form): #設(shè)置界面
Form.setObjectName("Form")
Form.resize(817, 630)
self.horizontalLayoutWidget = QtWidgets.QWidget(Form)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(10,20,801,611))
self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout.setObjectName("horizontalLayout")
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.label = QtWidgets.QLabel(self.horizontalLayoutWidget)
self.label.setMinimumSize(QtCore.QSize(330, 50))
font = QtGUI.QFont()
font.setFamily("漢儀唐美人W")
font.setPointSize(36)
font.setUnderline(False)
self.label.setFont(font)
self.label.setWordWrap(False)
self.label.setObjectName("label")
self.verticalLayout_3.addWidget(self.label)
self.graphicsView=QtWidgets.QGraphicsView(self.horizontalLayoutWidget)
self.graphicsView.setObjectName("graphicsView")
self.verticalLayout_3.addWidget(self.graphicsView)
self.pushButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)
font = QtGUI.QFont()
font.setFamily("漢儀唐美人W")
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.pushButton.setMinimumSize(QtCore.QSize(20, 50))
self.verticalLayout_3.addWidget(self.pushButton)
self.horizontalLayout.addLayout(self.verticalLayout_3)
self.verticalLayout_4 = QtWidgets.QVBoxLayout()
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.label_2 = QtWidgets.QLabel(self.horizontalLayoutWidget)
self.label_2.setMinimumSize(QtCore.QSize(330, 50))
font = QtGUI.QFont()
font.setFamily("漢儀唐美人W")
font.setPointSize(36)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.verticalLayout_4.addWidget(self.label_2)
self.textBrowser= QtWidgets.QTextBrowser(self.horizontalLayoutWidget)
self.textBrowser.setObjectName("textBrowser")
self.verticalLayout_4.addWidget(self.textBrowser)
self.pushButton_2= QtWidgets.QPushButton(self.horizontalLayoutWidget)
font = QtGUI.QFont()
font.setFamily("漢儀唐美人W")
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_2.setMinimumSize(QtCore.QSize(20, 50))
self.verticalLayout_4.addWidget(self.pushButton_2)
self.horizontalLayout.addLayout(self.verticalLayout_4)
self.retranslateUi(Form)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
self.pushButton_2.clicked.connect(self.on_pushButton_2_clicked)
QtCore.QMetaObject.connectSlotsByName(Form)
def on_pushButton_clicked(self):
#get the image path and show it in the view
self.face_recognize_object = my_face_recognition()
fileName, filetype = QFileDialog.getOpenFileName(None, "選擇文件", r"此處需要填寫文件路徑的起點", "Images (*.png *.jpg)")
self.imgPath=fileName
print (self.imgPath)
if self.imgPath != '':
self.face_recognize_object.operates_(self.imgPath)
if self.showFullImage == True:
self.face_recognize_object.showImg('original')
scene = QGraphicsScene() #創(chuàng)建場景
pixmap = QtGUI.QPixmap(self.imgPath)
#調(diào)用QtGUI.QPixmap方法,打開一個圖片,存放在變量中
scene.addItem(QtWidgets.QGraphicsPixmapItem(pixmap))
#添加圖片到場景中
self.graphicsView.setScene(scene)
#將場景添加到graphicsView中
self.graphicsView.show()
#顯示
self.textBrowser.clear()
self.textBrowser.append(str(self.face_recognize_object.errdet))
#輸出圖片是否合法
def on_pushButton_2_clicked(self):
self.face_recognize_object.AI()
self.brand=self.face_recognize_object.register_lps
self.color=self.face_recognize_object.register_rgb
print(self.brand)
self.textBrowser.clear()
self.textBrowser.append(str(self.face_recognize_object.errdet))
#輸出錯誤信息,若圖片不合法則在引用的函數(shù)返回為空。若圖片合法則會繼續(xù)輸出,看到口紅信息
strout="最像您輸入口紅的三只色號庫內(nèi)口紅分別為!"
flag=0 #設(shè)定flag用于檢測是否非法
for i in range(len(self.brand)):
flag=1 #如果是合法輸入,那么flag就會置1,后續(xù)不會提示錯誤
strout=strout+'\n'
print("flag1")
for j in range(len(self.brand[i])):
if(self.brand[i][j]!='none'):
strout=strout+str(self.brand[i][j])
self.textBrowser.append(strout)
if(flag==0):
self.textBrowser.clear()
self.textBrowser.append("這張圖片不可以進行處理,請換一張吧")
print("flag0")
#一些有關(guān)UI的固定操作,來自ui->py文件的轉(zhuǎn)換器
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", " Original pic"))
self.pushButton.setText(_translate("Form", "選擇文件"))
self.label_2.setText(_translate("Form", " result"))
self.pushButton_2.setText(_translate("Form", "開始識別"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
8)將流程封裝為類和函數(shù)
將之前描述的主流程代碼封裝為一個類,通過UI_*.py
程序調(diào)用這個類中的函數(shù)實現(xiàn)相關(guān)分類:
def operates_(self,input_path):
self.imgPath=input_path #展示圖片
def AI(self):
self.load_pic()
self.get=self.get_dominant_color(self.resultImg)
print("the extracted RGB value of the color is {0}".format(self.get))
self.data_operate()
def errordetect(self): #錯誤處理
image = face_recognition.load_image_file(self.imgPath)
face_locations = face_recognition.face_locations(image)
if(len(face_locations)!=1): #不是僅有一張人臉在圖片中
if(len(face_locations)==0): #未檢測到
self.errdet="more/less than one face in the pic"
return "can't find people"
else:#不只一個人
self.errdet="more/less than one face in the pic"
return "more/less than one face in the pic"
else:
return "DEAL"
9)對GUI的顯示效果進行美化
通過一個小組件對GUI的風格進行轉(zhuǎn)換,改變GUI的外觀。引入QCandyUi包:
from QCandyUi import CandyWindow
#調(diào)整按鈕的大小使之更清晰可見
self.pushButton.setMinimumSize(QtCore.QSize(20, 50))
self.pushButton_2.setMinimumSize(QtCore.QSize(20, 50))
#改變定義窗口類的調(diào)用方式
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog = CandyWindow.createWindow(Dialog, 'pink') #增加,使QCandyUi運行
Dialog.show()
sys.exit(app.exec_())
系統(tǒng)測試
未進行操作時的圖形化界面如圖所示。
運行程序,當輸入一張合規(guī)的照片,即輸入一張有且只有一個可識別面孔時,右側(cè)文本框中顯示的DEAL,如圖所示。
單擊“開始識別”,輸出的對應(yīng)色號如圖所示。
對比得到的色號和官網(wǎng)試色圖,如圖所示。
若不符合輸入照片要求會出現(xiàn)錯誤提示,單擊“開始識別”
后會彈出不可識別的提示,如下兩圖所示。
工程源代碼下載
詳見本人博客資源下載頁文章來源:http://www.zghlxwxcb.cn/news/detail-733526.html
其它資料下載
如果大家想繼續(xù)了解人工智能相關(guān)學習路線和知識體系,歡迎大家翻閱我的另外一篇博客《重磅 | 完備的人工智能AI 學習——基礎(chǔ)知識學習路線,所有資料免關(guān)注免套路直接網(wǎng)盤下載》
這篇博客參考了Github知名開源平臺,AI技術(shù)平臺以及相關(guān)領(lǐng)域?qū)<遥篋atawhale,ApacheCN,AI有道和黃海廣博士等約有近100G相關(guān)資料,希望能幫助到所有小伙伴們。文章來源地址http://www.zghlxwxcb.cn/news/detail-733526.html
到了這里,關(guān)于基于Dlib+PyQt5+TensorFlow智能口紅色號檢測推薦系統(tǒng)——深度學習算法應(yīng)用(含Python全部工程源碼及模型)+數(shù)據(jù)集的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!