2022-11-10|閱讀時間 ‧ 約 6 分鐘

掌紋辨識

取得掌紋

import cv2
image = cv2.imread("h_test.png")
cv2.imshow("palm",image) #to view the palm in python
cv2.waitKey(0)

#轉換爲灰度
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

#Canny Edge Detector的過濾算法來查找掌紋
edges = cv2.Canny(gray,60,65,apertureSize = 3)
cv2.imshow("edges",edges)
cv2.waitKey(0)

#反轉顏色,識別線條是黑色
edges = cv2.bitwise_not(edges)
cv2.imshow("change black and white",edges)
cv2.waitKey(0)

#黑色線條圖像與原始圖像混合
cv2.imwrite("palmlines.jpg", edges)
palmlines = cv2.imread("palmlines.jpg")
img = cv2.addWeighted(palmlines, 0.3, image, 0.7, 0)
cv2.imshow("lines in palm", img)
cv2.waitKey(0)

圖片比對

#用模板圖片去尋找圖片中的物件
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image, ImageDraw, ImageFont

#讀入原圖和模板
image = cv.imread("h_test.png")
img_rgb = cv.imread('palmlines.jpg') #原圖
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
template = cv.imread('p01.jpg',0) #比對用圖
w, h = template.shape[::-1]

# 讓視窗可以自由縮放大小
cv.namedWindow('TEST', cv.WINDOW_NORMAL)

#標準相關模板匹配
res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)
threshold = 0.4
loc = np.where( res >= threshold) # 匹配程度大於%40的坐標y,x
for pt in zip(*loc[::-1]): # *號表示可選參數
    cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,0), 2)
#cv.rectangle 畫框線
    
cv.imwrite('res.png',img_rgb)

# 顯示圖片
img = cv.imread('res.png')

#黑色線條圖像與原始圖像混合
img_ok = cv.addWeighted(img, 0.3, image, 0.7, 0)

def cv2ImgAddText(img_ok, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img_ok, np.ndarray)):  #判断是否OpenCV图片类型
        img_ok = Image.fromarray(cv.cvtColor(img_ok, cv.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img_ok)
    fontText = ImageFont.truetype(
        "font/simsun.ttc", textSize, encoding="utf-8")
    draw.text((left, top), text, textColor, font=fontText)
    return cv.cvtColor(np.asarray(img_ok), cv.COLOR_RGB2BGR)

img_txt = cv2ImgAddText(img_ok, "生命線", pt[0] ,  pt[1]-30 , (255, 0, 0), 20)
cv.imshow('TEST', img_txt)

#imagex = cv.imread("res.png")
#cv.imshow("ok",imagex)
cv.waitKey(0)
後續思維...
透過特徵比對+CNN,以YOLO 或 TensorFlow+Keras進行會比較正確。
單靠OpneCV至此是極限,要判斷出各條線,沒模型,則要以numpy陣列加上相似度(哈希算法等)去做,整體上不好進行...
待續...
分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.