本篇文章以模板匹配算法为例,使用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)
1 条评论
陈哥璩:文章真不错http://wap.jst-gpmx.cn/news/30199.html