学习opencv: 鼠标提取矩形(Rectangle)ROI

  • 方法:获取鼠标点击事件

  • 代码

    # import the necessary packages
    import argparse
    import cv2
    # initialize the list of reference points and boolean indicating
    # whether cropping is being performed or not
    refPt = []
    cropping = False
    def click_and_crop(event, x, y, flags, param):
    	# grab references to the global variables
    	global refPt, cropping
    	# if the left mouse button was clicked, record the starting
    	# (x, y) coordinates and indicate that cropping is being
    	# performed
    	if event == cv2.EVENT_LBUTTONDOWN:
    		refPt = [(x, y)]
    		cropping = True
    	# check to see if the left mouse button was released
    	elif event == cv2.EVENT_LBUTTONUP:
    		# record the ending (x, y) coordinates and indicate that
    		# the cropping operation is finished
    		refPt.append((x, y))
    		cropping = False
    		# draw a rectangle around the region of interest
    		cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
    		cv2.imshow("image", image)
    
    
    # construct the argument parser and parse the arguments
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--image", required=True, help="Path to the image")
    args = vars(ap.parse_args())
    # load the image, clone it, and setup the mouse callback function
    image = cv2.imread(args["image"])
    clone = image.copy()
    cv2.namedWindow("image")
    cv2.setMouseCallback("image", click_and_crop)
    # keep looping until the 'q' key is pressed
    while True:
    	# display the image and wait for a keypress
    	cv2.imshow("image", image)
    	key = cv2.waitKey(1) & 0xFF
    	# if the 'r' key is pressed, reset the cropping region
    	if key == ord("r"):
    		image = clone.copy()
    	# if the 'c' key is pressed, break from the loop
    	elif key == ord("c"):
    		break
    # if there are two reference points, then crop the region of interest
    # from teh image and display it
    if len(refPt) == 2:
    	roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
    	cv2.imshow("ROI", roi)
    	cv2.waitKey(0)
    # close all open windows
    cv2.destroyAllWindows()
    
  • 结果
    结果

参考资料

https://github.com/xuyangcao/random_walker_gui
Capturing mouse click events with Python and OpenCV

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

此人姓于名叫罩百灵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值