20200611

 

참고자료

"https://zzsza.github.io/data/2018/01/23/opencv-1/" OpenCV함수 설명

"https://github.com/VivekKrG/Image-field-detection-using-template-matching-using-openCV"

"https://sungwookkang.com/m/1404" 성별 나이 맞추기

 

01 Image Field Detection

library설치 ; imutils

 

attached file

gad.zip

code

# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 22:28:42 2020

@author: KDB
"""


# importing libraries 
import numpy as np 
import imutils 
import cv2 

field_threshold = { "prev_policy_no" : 0.7, 
					"address"	 : 0.6, 
				} 

# Function to Generate bounding 
# boxes around detected fields 
def getBoxed(img, img_gray, template, field_name = "policy_no"): 

	w, h = template.shape[::-1] 

	# Apply template matching 
	res = cv2.matchTemplate(img_gray, template, 
						cv2.TM_CCOEFF_NORMED) 

	hits = np.where(res >= field_threshold[field_name]) 

	# Draw a rectangle around the matched region. 
	for pt in zip(*hits[::-1]): 
		cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), 
									(0, 255, 255), 2) 

		y = pt[1] - 10 if pt[1] - 10 > 10 else pt[1] + h + 20

		cv2.putText(img, field_name, (pt[0], y), 
			cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 1) 

	return img 


# Driver Function 
if __name__ == '__main__': 

	# Read the original document image 
	img = cv2.imread('doc.png') 
		
	# 3-d to 2-d conversion 
	img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
	
	# Field templates 
	template_add = cv2.imread('doc_address.png', 0) 
	template_prev = cv2.imread('doc_prev_policy.png', 0) 

	img = getBoxed(img.copy(), img_gray.copy(), 
					template_add, 'address') 

	img = getBoxed(img.copy(), img_gray.copy(), 
				template_prev, 'prev_policy_no') 

	cv2.imshow('Detected', img)
cv2.waitKey(0)

02 성별 나이 맞추기

gad.py

(base)pip install opencv-python

import cv2
import math
import argparse

def highlightFace(net, frame, conf_threshold=0.7):
    frameOpencvDnn=frame.copy()
    frameHeight=frameOpencvDnn.shape[0]
    frameWidth=frameOpencvDnn.shape[1]
    blob=cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], True, False)

    net.setInput(blob)
    detections=net.forward()
    faceBoxes=[]
    for i in range(detections.shape[2]):
        confidence=detections[0,0,i,2]
        if confidence>conf_threshold:
            x1=int(detections[0,0,i,3]*frameWidth)
            y1=int(detections[0,0,i,4]*frameHeight)
            x2=int(detections[0,0,i,5]*frameWidth)
            y2=int(detections[0,0,i,6]*frameHeight)
            faceBoxes.append([x1,y1,x2,y2])
            cv2.rectangle(frameOpencvDnn, (x1,y1), (x2,y2), (0,255,0), int(round(frameHeight/150)), 8)
    return frameOpencvDnn,faceBoxes


parser=argparse.ArgumentParser()
parser.add_argument('--image')

args=parser.parse_args()

faceProto="opencv_face_detector.pbtxt"
faceModel="opencv_face_detector_uint8.pb"
ageProto="age_deploy.prototxt"
ageModel="age_net.caffemodel"
genderProto="gender_deploy.prototxt"
genderModel="gender_net.caffemodel"

MODEL_MEAN_VALUES=(78.4263377603, 87.7689143744, 114.895847746)
ageList=['(0-2)', '(4-6)', '(8-12)', '(15-20)', '(25-32)', '(38-43)', '(48-53)', '(60-100)']
genderList=['Male','Female']

faceNet=cv2.dnn.readNet(faceModel,faceProto)
ageNet=cv2.dnn.readNet(ageModel,ageProto)
genderNet=cv2.dnn.readNet(genderModel,genderProto)

video=cv2.VideoCapture(args.image if args.image else 0)
padding=20
while cv2.waitKey(1)<0:
    hasFrame,frame=video.read()
    if not hasFrame:
        cv2.waitKey()
        break

    resultImg,faceBoxes=highlightFace(faceNet,frame)
    if not faceBoxes:
        print("No face detected")

    for faceBox in faceBoxes:
        face=frame[max(0,faceBox[1]-padding):
                   min(faceBox[3]+padding,frame.shape[0]-1),max(0,faceBox[0]-padding)
                   :min(faceBox[2]+padding, frame.shape[1]-1)]

        blob=cv2.dnn.blobFromImage(face, 1.0, (227,227), MODEL_MEAN_VALUES, swapRB=False)
        genderNet.setInput(blob)
        genderPreds=genderNet.forward()
        gender=genderList[genderPreds[0].argmax()]
        print(f'Gender: {gender}')

        ageNet.setInput(blob)
        agePreds=ageNet.forward()
        age=ageList[agePreds[0].argmax()]
        print(f'Age: {age[1:-1]} years')

        cv2.putText(resultImg, f'{gender}, {age}', (faceBox[0], faceBox[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,255), 2, cv2.LINE_AA)
        cv2.imshow("Detecting age and gender", resultImg)
Posted by Weneedu
,


출처: https://privatedevelopnote.tistory.com/81 [개인노트]