import os
import cv2
import numpy as np
import tensorflow as tf
import sys
detection_graph = tf.Graph()
model_file = "./tag_detect/finger_stamp.pb"
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(model_file, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config, graph=detection_graph)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
def red_check(cropped):
h,s,v = cv2.split(cv2.cvtColor(cropped,cv2.COLOR_BGR2HSV))
h_min_0 = 0
h_max_0 = 10
h_min_1 = 156
h_max_1 = 180
s_min = 43
s_max = 255
v_min = 46
v_max = 255
h_0 = cv2.inRange(h,h_min_0 , h_max_0)
h_1 = cv2.inRange(h,h_min_1 , h_max_1)
s_ = cv2.inRange(s,s_min, s_max)
v_= cv2.inRange(v,v_min, v_max)
h_ = cv2.bitwise_or(h_0,h_1)
all_ = h_&s_&v_
red_ratio = (all_ == 255).sum()/float(cropped.shape[0]*cropped.shape[1])
#print(all_.shape)
#print(type(all_))
#print(all_.dtype)
#print('red_check' ,red_ratio)
if red_ratio>0.02:
return u"是"
return u"否"
def get(image, thresh = 0.5):
h,w,c = image.shape
res = {"finger":u"否", "stamp":u"否", "sign":u"否"}
resized_dp = 960.0/h
image_resized = cv2.resize(image,None,fx = resized_dp, fy = resized_dp)
image = cv2.cvtColor(image_resized,cv2.COLOR_BGR2RGB)
image_expanded = np.expand_dims(image, axis=0)
out = sess.run([num_detections,detection_scores,detection_boxes,detection_classes],
feed_dict={image_tensor: image_expanded})
num = int(out[0][0])
rows,cols,_= image.shape
for i in range(num):
classId = int(out[3][0][i])
score = float(out[1][0][i])
bbox = [float(v) for v in out[2][0][i]]
if score > thresh:
x = int(bbox[1] * cols)
y = int(bbox[0] * rows)
right = int(bbox[3] * cols)
bottom = int(bbox[2] * rows)
cropped = image_resized[y:bottom,x:right]
if classId == 1:
if res['finger'] == u"是":
continue
res['finger'] = red_check(cropped)
res['sign'] = res['finger']
continue
elif classId == 2:
if res['stamp'] == u"是":
continue
res['stamp'] = red_check(cropped)
continue
return res
if __name__ == "__main__":
image = cv2.imread(sys.argv[1])
image_expanded = np.expand_dims(image, axis=0)
ret = get(image)
print(ret)