Tip:应用鼠标事件画出一个矩形框,再对像素点进行反转
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 26 16:30:20 2018
@author: Miracle
"""
import cv2
def drawRectangle(event,x,y,flags,params):
global init_x,init_y,drawing,point_top_left,point_bottom_right
#鼠标响应
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
init_x,init_y = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
point_top_left = (min(init_x,x),min(init_y,y))
point_bottom_right = (max(init_x,x),max(init_y,y))
image[init_y:y,init_x:x] = 255 - image[init_y:y,init_x:x]
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
point_top_left = (min(init_x,x),min(init_y,y))
point_bottom_right = (max(init_x,x),max(init_y,y))
image[init_y:y,init_x:x] = 255 - image[init_y:y,init_x:x]
if __name__ == '__main__':
drawing = False
point_bottom_right,point_top_left = (-1,-1),(-1,-1)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise IOError('Cannot open webcam!')
cv2.namedWindow('webcam')
cv2.setMouseCallback('webcam',drawRectangle)
while True:
ret,frame = cap.read()
image = cv2.resize(frame,None,fx = 1.25,fy = 1.25,
interpolation = cv2.INTER_LINEAR)
(x0,y0),(x1,y1) = point_top_left,point_bottom_right
image[y0:y1,x0:x1] = 255 - image[y0:y1,x0:x1]
cv2.imshow('webcam',image)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()