• 카테고리

    질문 & 답변
  • 세부 분야

    컴퓨터 비전

  • 해결 여부

    해결됨

사각형 부분과 사진변경이 되지 않습니다.

20.10.18 14:09 작성 조회수 188

0

import cv2

import numpy as np

from tkinter import *

from PIL import Image

from PIL import ImageTk

from tkinter import filedialog

model_name = 'res10_300x300_ssd_iter_140000.caffemodel'

prototxt_name = 'deploy.prototxt.txt'

min_confidence = 0.5

file_name = "image/aa.jpg"

title_name = "dnn Deep Learning object detection"

frame_width = 300

frame_height = 300

def selectFile():

    file_name = filedialog.askopenfilename(initialdir = "./image", title = "Select file", filetypes = (("jpeg files","*.jpg"),("all files","*.*")))

    print('File name: ', file_name)

    read_image = cv2.imread(file_name)

    image = cv2.cvtColor(read_image, cv2.COLOR_BGR2RGB)

    image = Image.fromarray(image)

    imgtk = ImageTk.PhotoImage(image=image)

    (height, width) = read_image.shape[:2]

    detectAndDisplay(read_image, width, height)

    

    

def detectAndDisplay(frame,w,h):

    model = cv2.dnn.readNetFromCaffe(prototxt_name, model_name)

    blob = cv2.dnn.blobFromImage(cv2.resize((frame),(300,300)), 1.0, (300,300), (104.0, 177.0, 123.0))

    model.setInput(blob)

    detections = model.forward()

    minConfidence = float(sizeSpin.get())

    for i in range(0, detections.shape[2]):

        confidence = detections[0, 0, i, 2]

        if confidence > min_confidence:

            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h ])

            (startX, startY, endX, endY) = box.astype("int")

            text = "{:.2f}%".format(confidence * 100)

            y = startY - 10 if startY - 10 > 10 else startY + 10 #박스 시작점 10 위에 text를 넣는다. 10을 더했을 때 화면을 넘어가면 아래에 표시

            cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 2)

            cv2.putText(frame, text, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0 ), 1)

    image = cv2.cvtColor(frame , cv2.COLOR_BGR2RGB)

    image = Image.fromarray(image)

    imatk = ImageTk.PhotoImage(image=image)

    detection.config(image=imgtk)

    detection.image = imgtk

main = Tk()

main.title(title_name)

main.geometry()

read_image = cv2.imread(file_name)

image = cv2.cvtColor(read_image , cv2.COLOR_BGR2RGB)

image = Image.fromarray(image)

imgtk = ImageTk.PhotoImage(image=image)

(height, width) = read_image.shape[:2]

label = Label(main, text=title_name)

label.config(font=("Courier",18))

label.grid(row=0, column=0, columnspan=4)

sizeLabel=Label(main, text='Min Confidence :')

sizeLabel.grid(row=1,column=0)

sizeVal = IntVar(value=min_confidence)

sizeSpin = Spinbox(main, textvariable=sizeVal, from_=0, to= 1, increment=0.05, justify=RIGHT)

sizeSpin.grid(row=1, column=1)

Button(main, text = 'File Select', height=2, command=lambda:selectFile()).grid(row=1, column=2, columnspan= 4)

detection = Label(main, image = imgtk)

detection.grid(row=2,column=0, columnspan=4)

detectAndDisplay(read_image,width,height)

main.mainloop()

이렇게 코드를 작성하였고 파일경로도 다 확인하였기에 실행은 되지만 실행결과가

이런 식으로 사각형 틀이 없게 작동됩니다.

GUI방식 말고 전 강의 처럼 cv2.imshow("Face Detection by dnn", frame) 를 하면

이렇게 잘 작동이 됩니다.

그리고 파일을 변경하려고 하면

이런 식으로 file name은 출력이 되지만 GUI는 사진이 바뀌지 않고 그대로 입니다. 어떤 부분이 잘못된 것인지 알려주시면 감사하겠습니다!

답변 4

·

답변을 작성해보세요.

0

Lee JaeJun님의 프로필

Lee JaeJun

질문자

2020.10.20

다시 코드를 검토하던 중에 imgtk = ImageTk.PhotoImage(image=image)가 imatk로 오타가 있던 것을 확인했습니다! 수정후 잘 실행이됩니다. 친절하게 도와주셔서 감사합니다:)

0

안녕하세요?
print(confidence)를 실행하는 것은 조치를 하기 위해서가 아니고 원인을 파악해 보기 위해서입니다.

맨 위에 0.6054...라고 나오는 것을 보면 정상적으로 출력되어야 하는데 안나오는 것을 보면 

        if confidence > min_confidence:

            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h ])

            (startX, startY, endX, endY) = box.astype("int")

            text = "{:.2f}%".format(confidence * 100)

위에서 print('1. ', confidence, min_confidence)를 하고

아래에서 역시 print('2. ',confidence, min_confidence, text)를 해보세요.

그렇게 원인을 찾아나가다 보면 답을 찾을 수 있을 겁니다.

실행해 보고 결과 알려주세요.

감사합니다.

0

Lee JaeJun님의 프로필

Lee JaeJun

질문자

2020.10.19

말씀해주신 대로 print(confidence)를 추가하니

이런 식으로 실수들이 나오는 것을 확인했습니다. 하지만 여전히 잘 작동하지 않는 것 같습니다 :(

0

안녕하세요?
코드만 봐서는 정상인것 같은데 GUI에서 동작을 안한다니 이상하네요.

단, GUI프로그램이 학습용으로 제작되어 모든 예외상황을 고려하지는 않았습니다.

그래도 처음 실행할 떄는 정상적으로 작동이 되어야 하는데요. 

for i in range(0, detections.shape[2]):

        confidence = detections[0, 0, i, 2]

아래에 print(confidence)와 같이 실행되는 지 명령창에서 확인해 보시겠어요?

확인 후 알려주시면 원인을 같이 찾아보겠습니다.

감사합니다.