반응형
Problem
OpenCV로 촬영 혹은 가져온 사진을 PIL을 이용해서 가공하려고하면 에러가 뜬다. 아마 int is not subscriptable이라고 뜰 것이다.
일부러 일으켜보니 'int' object is not subscriptable 이었다.
Solution
이를 해결하기 위해서는 opencv 이미지 자료형을 PIL에 맞도록 변환해야하는데, 이를 위해서는 두 가지 과정을 거쳐야한다.
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img=Image.fromarray(img)
BGR을 RGB로 순서를 바꿔주고, PIL.Image.fromarray(img)로 PIL에 맞는 자료형으로 변환한다.
정리
소스코드 총집본?은 다음과 같다.
아, 참고로 기존에 있던 물체 인식 모델을 가져와서 인식하는 프로그램이다.
import cv2
from keras.models import load_model
from PIL import Image, ImageOps
import numpy as np
# Set WebCam
frameWidth = 640
frameHeight = 480
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth) # Width
cap.set(4, frameHeight) # Height
cap.set(10, 150) # Brightness
# Load the model
model = load_model('keras_model.h5')
while True:
# take picture
success, img = cap.read()
cv2.imshow("", img)
# data preprocessing
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
size = (224, 224)
# OpenCV to PIL image
# convert from BGR to RGB & from openCV2 to PIL
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img=Image.fromarray(img)
# PIL image processiing
image = ImageOps.fit(img, size, Image.ANTIALIAS)
image_array = np.asarray(image)
normalized_image_array = (image_array.astype(np.float32) / 127.) - 1
data[0] = normalized_image_array
# predicting
prediction = model.predict(data)
print("Pen", prediction[0,0])
print("Key", prediction[0,1])
print("Vaseline", prediction[0,2])
# expiration
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
reference
반응형