Skip to content

Instantly share code, notes, and snippets.

@naoki-sawada
Created March 3, 2018 13:53
Show Gist options
  • Save naoki-sawada/4398775bd12e47400c0aadc88097f1f0 to your computer and use it in GitHub Desktop.
Save naoki-sawada/4398775bd12e47400c0aadc88097f1f0 to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
from keras.applications.mobilenet import MobileNet
from keras.preprocessing import image
from keras.applications.mobilenet import preprocess_input, decode_predictions
IMG_SIZE = 224
IMG_NAME = 'photo.jpg'
model = MobileNet(weights='imagenet')
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
height, width = frame.shape[:2]
crop_img = frame[
int(round((height/2)-IMG_SIZE)):int(round((height/2)+IMG_SIZE)),
int(round((height/2)-IMG_SIZE)):int(round((height/2)+IMG_SIZE))]
cv2.imwrite(IMG_NAME, crop_img)
img = image.load_img(IMG_NAME, target_size=(IMG_SIZE, IMG_SIZE))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
print('Predicted:', decode_predictions(preds, top=3)[0])
cv2.imshow('sample', crop_img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment