使用鼠标事件绘制模糊的矩形 [英] Draw blurred rectangles using mouse events

查看:92
本文介绍了使用鼠标事件绘制模糊的矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码仅在拖动鼠标时才绘制矩形,但是我只想模糊从鼠标绘制的矩形区域.

Below code just draws rectangles, whenever mouse is dragged, but I want to blur only rectangle region that is drawn from mouse.

import cv2
import argparse

ref_point = []


def shape_selection(event,x,y,flags,param):
    global ref_point, crop

    if event == cv2.EVENT_LBUTTONDOWN:
        ref_point = [(x,y)]


    elif event == cv2.EVENT_LBUTTONUP:
        ref_point.append((x,y))
        #cv2.GaussianBlur(image,(9,9),0)
        cv2.rectangle(image,ref_point[0],ref_point[1],(0,255,0),2)
        #cv2.GaussianBlur(images,(9,9),0)
        cv2.imshow("image",image)

ap=argparse.ArgumentParser()
ap.add_argument("-i","--image",required=True,help="Path to image")
args=vars(ap.parse_args())

image = cv2.imread(args["image"])
clone=image.copy()
#cv2.GaussianBlur(image,(9,9),0)
cv2.namedWindow("image")
cv2.setMouseCallback("image",shape_selection)

while True:
    cv2.imshow("image",image)
    key = cv2.waitKey(1) & 0xFF
    if key == ord("r"):
        image=clone.copy()
    elif key == ord("c"):
        break

cv2.destroyAllWindows()

推荐答案

主要的技巧"是仅在图像的感兴趣区域(ROI)上使用GaussianBlur方法.通过适当的NumPy 数组索引,可以访问"Python OpenCV图像"中的矩形ROI.和切片.大多数OpenCV函数(Python API)都支持仅在这些ROI上进行操作.

The main "trick" is to use the GaussianBlur method just on the region of interest (ROI) of the image. Accessing rectangular ROIs in "Python OpenCV images" is done by proper NumPy array indexing and slicing. Operations solely on these ROIs are supported by most OpenCV functions (Python API).

因此,这可能是您的shape_selection方法的修改版本:

So, that might be a modified version of your shape_selection method:

def shape_selection(event, x, y, flags, param):
    global image, ref_point

    if (event == cv2.EVENT_LBUTTONDOWN):
        ref_point = [(x, y)]

    elif (event == cv2.EVENT_LBUTTONUP):
        (x_ref, y_ref) = ref_point[0]

        if (x_ref > x):
            (x, x_ref) = (x_ref, x)
        if (y_ref > y):
            (y, y_ref) = (y_ref, y)

        image[y_ref:y, x_ref:x] = cv2.GaussianBlur(image[y_ref:y, x_ref:x], (9, 9), 0)
        image = cv2.rectangle(image, (x_ref, y_ref), (x, y), (0, 255, 0), 2)
        cv2.imshow('image', image)

如果从右到左"或从下到上"绘制矩形,则必须将两个记录点的xy坐标交换为适当的切片.

If you draw rectangles "from right to left" or "from bottom to top", the x and y coordinates of the two recorded points must be swapped for a proper slicing.

希望有帮助!

这篇关于使用鼠标事件绘制模糊的矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆