1. 鼠标回调函数缩放图片
import cv2
class Param:
def __init__(self, img):
self.img = img
self.scale = 0.8
self.src = cv2.resize(img,
(int(img.shape[1] * self.scale), int(img.shape[0] * self.scale)),
cv2.INTER_AREA)
def lbuttondown(self, x, y):
self.lmove_from = (x, y)
print("-lbuttondown>", round(x / self.scale), round(y / self.scale))
def rbuttondown(self):
print("->rbuttondown")
def mousewheel(self, flags):
self.scale += flags / abs(flags) / 50
if self.scale < 0.5:
self.scale = 0.5
elif self.scale > 2:
self.scale = 2
w = int(self.img.shape[1] * self.scale)
h = int(self.img.shape[0] * self.scale)
self.src = cv2.resize(self.img, (w, h), cv2.INTER_AREA)
else:
src_cropped = self.src[0 : self.img.shape[1], 0 : self.img.shape[0]]
cv2.imshow('ABC', src_cropped)
def flag_lbutton(self, x, y):
pass
self.lmove_to = (x, y)
move_vector = tuple(map(lambda x: x[0]-x[1], zip(self.lmove_to, self.lmove_from)))
right_boundary = self.src.shape[1] - move_vector[1]
top_boundary = self.src.shape[0] - move_vector[0]
if right_boundary < 0:
right_boundary = 0
elif right_boundary > self.src.shape[1] - self.img.shape[1]:
right_boundary = self.src.shape[1] - self.img.shape[1]
if top_boundary < 0:
top_boundary = 0
elif top_boundary > self.src.shape[0] - self.img.shape[0]:
top_boundary = self.src.shape[0] - self.img.shape[0]
src_moved = self.src[right_boundary : (right_boundary + self.img.shape[1]),
top_boundary : (top_boundary + self.img.shape[0])]
print("->flag_lbutton:", move_vector)
cv2.imshow('ABC', src_moved)
def mouse(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
param.lbuttondown(x, y)
elif event == cv2.EVENT_RBUTTONDOWN:
param.rbuttondown()
elif event == cv2.EVENT_MOUSEWHEEL:
param.mousewheel(flags)
elif flags == cv2.EVENT_FLAG_LBUTTON:
param.flag_lbutton(x, y)
if __name__ == '__main__':
img = cv2.imread('1.jpg')
param = Param(img)
cv2.namedWindow('ABC', cv2.WINDOW_NORMAL)
cv2.setMouseCallback('ABC', mouse, param)
cv2.waitKey(0)
cv2.destroyAllWindows()