如何使用opencv读取ImageTk.PhotoImage

时间:2019-06-21 11:00:56

标签: python-3.x opencv tkinter

我正在将基本图像加载到ImageTk.PhotoImage中,然后使用该图像运行opencv模板匹配功能,到目前为止,它已经起作用了……但是我需要检查几个模板,我想要在同一结果图像中创建模板矩形,如何使用opencv从ImageTk.PhotoImage读取图像?

嗯...我想我需要采取相反的方式,将PhotoImage内容转换为数组...但是我不知道该怎么做!

将图像加载到PhotoImage

def select_BaseImage():
    global imgBase, imgBasePath
    path = filedialog.askopenfilename()
    if len(path) > 0:
        imgBasePath = path
        image = cv2.imread(path)
        image = Image.fromarray(image)
        image = ImageTk.PhotoImage(image)

        if imgBase is None:
            imgBase = Label(image=image)
            imgBase.image = image
            imgBase.pack(side="left", padx=10, pady=10)
        # otherwise, update the image panels
        else:
            # update the pannels
            imgBase.configure(image=image)
            imgBase.image = image

处理图像

def process_Image():
    img = cv2.imread(imgBasePath,0)
    template = cv2.imread(imgTargetPath,0)
    w, h = template.shape[::-1]

    # Apply template Matching
    res = cv2.matchTemplate(img,template,cv2.TM_CCORR_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)

    # Show the result
    image = cv2.imread(imgBasePath)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    cv2.rectangle(image,top_left, bottom_right, (0,255,0), 2)
    image = Image.fromarray(image)
    image = ImageTk.PhotoImage(image)
    imgBase.configure(image=image)
    imgBase.image = image

加载模板

def process_Script():
    itemList = script.sections()
    for item in itemList:
        select_TargetImage(script.get(item, 'Name')+".jpg")
        process_Image()

如果还有另一种方法,这将对我有所帮助,因为我是python和opencv的新手!

0 个答案:

没有答案