-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathview_crop.py
More file actions
73 lines (63 loc) · 2.68 KB
/
Copy pathview_crop.py
File metadata and controls
73 lines (63 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import cv2
import numpy as np
from key_codes import is_escape, is_enter
_F = cv2.FONT_HERSHEY_PLAIN
_st = {}
def on_enter(frames):
_st.clear()
_st.update({
"frames": list(frames),
"drag": {"active":False,"done":False,"x0":0,"y0":0,"x1":0,"y1":0},
"status": "Drag to select crop region | Enter=apply | Esc=cancel",
})
def render(canvas, ww, wh, events):
frames = _st["frames"]
drag = _st["drag"]
if not frames:
return {"to":"scrub","frames":frames}
_, ref = frames[0]
fh, fw = ref.shape[:2]
hint_h = 20
img_h = wh - hint_h
scale = min(ww/max(1,fw), img_h/max(1,fh))
nw = max(1,int(fw*scale)); nh = max(1,int(fh*scale))
ox = (ww-nw)//2; oy = (img_h-nh)//2
for ev,x,y,flags in events["mouse"]:
if ev==cv2.EVENT_LBUTTONDOWN:
drag.update({"active":True,"done":False,"x0":x,"y0":y,"x1":x,"y1":y})
elif ev==cv2.EVENT_MOUSEMOVE and drag["active"]:
drag["x1"]=x; drag["y1"]=y
elif ev==cv2.EVENT_LBUTTONUP and drag["active"]:
drag["x1"]=x; drag["y1"]=y
drag["active"]=False; drag["done"]=True
# draw reference frame
resized=cv2.resize(ref,(nw,nh),interpolation=cv2.INTER_NEAREST)
canvas[oy:oy+nh,ox:ox+nw]=resized
if drag["active"] or drag["done"]:
x0,y0=drag["x0"],drag["y0"]; x1,y1=drag["x1"],drag["y1"]
rx0,ry0=min(x0,x1),min(y0,y1); rx1,ry1=max(x0,x1),max(y0,y1)
if rx1>rx0 and ry1>ry0:
dim=canvas.copy()
dim=(dim*0.35).astype(np.uint8)
canvas[:]=dim
canvas[oy:oy+nh,ox:ox+nw]=resized
mask=np.zeros((wh,ww),dtype=np.uint8)
mask[ry0:ry1,rx0:rx1]=255
dark=(canvas.astype(np.float32)*0.35).astype(np.uint8)
canvas[mask==0]=dark[mask==0]
cv2.rectangle(canvas,(rx0,ry0),(rx1,ry1),(55,218,255),1)
fw_s=max(1,int((rx1-rx0)/scale)); fh_s=max(1,int((ry1-ry0)/scale))
cv2.putText(canvas,f"{fw_s}x{fh_s}",(rx0+4,max(ry0-5,12)),_F,0.9,(55,218,255),1)
cv2.putText(canvas,_st["status"],(8,wh-4),_F,0.85,(68,88,108),1)
k=events["key"]
if is_escape(k):
return {"to":"scrub","frames":frames}
if is_enter(k) and drag["done"]:
x0,y0=drag["x0"],drag["y0"]; x1,y1=drag["x1"],drag["y1"]
rx0=max(0,int((min(x0,x1)-ox)/scale)); ry0=max(0,int((min(y0,y1)-oy)/scale))
rx1=min(fw,int((max(x0,x1)-ox)/scale)); ry1=min(fh,int((max(y0,y1)-oy)/scale))
if rx1>rx0 and ry1>ry0:
new_frames=[(ts,f[ry0:ry1,rx0:rx1].copy()) for ts,f in frames]
return {"to":"scrub","frames":new_frames}
return {"to":"scrub","frames":frames}
return None