本篇文章以模板匹配算法为例,使用Gradio构建一个基于opencv的模板匹配算法交互界面。体现出使用gradio构建界面的基本逻辑和简单的界面布局,附源代码。

1. 首先在你的python环境中安装opencv和gradio

pip install opencv-python gradio

2. 写一个demo脚本,比如叫demo.py,其中源码如下:

import cv2
import gradio as gr

def temp_matching(src_img, x0, y0, x1, y1, match_method):

    img = cv2.cvtColor(src_img, cv2.COLOR_RGB2GRAY)

    temp1 = src_img.copy()[y0:y1, x0:x1]
    temp = cv2.cvtColor(temp1, cv2.COLOR_RGB2GRAY)

    th, tw = temp.shape[::]
    rv = cv2.matchTemplate(img, temp, eval(match_method))

    minV, maxV, minL, maxL = cv2.minMaxLoc(rv)
    topleft = minL
    bottomright = (topleft[0] + tw, topleft[1] + th)

    img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
    cv2.rectangle(img, (x0, y0), (x1, y1), (0, 255, 0), 2)
    cv2.rectangle(img, topleft, bottomright, (255, 0, 0), 2)
    cv2.rectangle(src_img, (x0, y0), (x1, y1), (0, 255, 0), 2)

    return [src_img, img]


if __name__=='__main__':

    with gr.Blocks() as demo:
        with gr.Column():
            with gr.Row():
                img = gr.Image(label="Ori IMG")
                with gr.Column():
                    with gr.Row():
                        num1 = gr.Number(label="x0")
                        num2 = gr.Number(label="y0")
                    with gr.Row():
                        num3 = gr.Number(label="x1")
                        num4 = gr.Number(label="y1")
                    method = gr.Dropdown(choices=["cv2.TM_SQDIFF_NORMED", "cv2.TM_SQDIFF", "cv2.TM_CCORR", "cv2.TM_CCORR_NORMED", "cv2.TM_CCOEFF", "cv2.TM_CCOEFF_NORMED"], label="请选择匹配算法", value="cv2.TM_SQDIFF_NORMED")
            btn = gr.Button(value='Match Now!')
            with gr.Row():
                img1 = gr.Image(label="Temp Box")
                img2 = gr.Image(label="Detected Box")
            btn.click(temp_matching, inputs=[img, num1, num2, num3, num4, method], outputs=[img1, img2])
    demo.launch(server_port=7860)

3. 在python环境中执行python demo.py运行demo,这里设置的端口号是7860,所以在浏览器地址栏访问127.0.0.1:7860即可打开gradio界面。在这里可以上传图片,设置模板区域,选择模板匹配所用算法,然后可视化模板匹配结果。具体见下图,绿框表示设置的模板,红框表示匹配算法检测出的区域(右边图像中红框完全覆盖住绿框,选择其它算法可看到不重叠的效果)。

最后修改:2024 年 05 月 18 日
如果觉得我的文章对你有用,请随意赞赏