Opencv Deep learning 이미지 인식
# readNet(model, config)
# cv2.dnn.readNet
# blobFromImage(image, scalefactor, size, mean, swapRB, crop) -> retval
# blob = cv2.dnn.blobFromImage
# net.setInput(blob)
# prob = net.forward()
########### googLeNet 영상인식
# 입력크기: 224 x 224 (224,224)
# 컬러: BGR
# 밝기평균값: (104, 117, 123)
# filename = ('./googlenet/fig/apple2.png')
filename = ('./googlenet/fig/Cat_November_2010-1a.jpeg')
img_files = glob.glob('./googlenet/fig/*.*')
img_lst = os.listdir('./googlenet/fig')
img_files = []
for i in img_lst:
img_file = './googlenet/fig/' + i
img_files.append(img_file)
cv2.namedWindow('img',cv2.WINDOW_NORMAL)
cv2.namedWindow('img',cv2.WINDOW_NORMAL)
cv2.setWindowProperty('img', cv2.WND_PROP_AUTOSIZE,cv2.WINDOW_AUTOSIZE)
img = cv2.imread(filename)
if img is None:
print('image read failed')
sys.exit()
#######################################################################################################
## dnn Model
model = './google/bvlc_googlenet.caffemodel'
config = './google/deploy.prototxt.txt'
net = cv2.dnn.readNet(model, config) # 객체 생성
idx = 0
while True:
if net.empty():
print('network fail')
sys.exit()
##클래스 이름 불러오기
classNames = []
with open('./google/classification_classes_ILSVRC2012.txt', 'rt') as f:
classNames = f.read().rstrip('\n').split('\n')
# print(classNames[200])
# blobFromImage(image, scalefactor, size, mean, swapRB, crop) -> retval
blob = cv2.dnn.blobFromImage(img,1,(224,224),(104, 117, 123),swapRB=False)
net.setInput(blob)
prob = net.forward()
#######################################################################################################
print(prob.shape) # 2D
out = prob.flatten()
print(out.shape)
classid = np.argmax(out)
print(classid)
confidence = out[classid]
print(confidence)
category = classNames[classid]
print(category)
text = f'{classNames[classid]} ({confidence*100:4.2f})%'
img = cv2.imread(img_files[idx])
cv2.putText(img, text, (100,30), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0,0, 255),2, cv2.LINE_AA)
cv2.imshow('img', img)
if cv2.waitKey(2000) == 27:
break
idx += 1
if idx >= len(img_files):
idx = 0
cv2.waitKey(1)
cv2.destroyAllWindows()
cv2.waitKey(1)