1.安裝元件
pip install opencv-python
2.參考程式碼
import cv2
import time,PIL,os
from PIL import ImageGrab
import numpy as np
import tkinter as tk
from tkinter import *
import win32clipboard as clip
from ctypes import *
import win32con
window = tk.Tk()
window.wm_attributes('-topmost',1) #固定最上層
window.wm_attributes('-toolwindow',1) #去除最大最小化按鈕
window.resizable(0,0) #禁止改變大小
window.title('螢幕截圖')
window.geometry("270x170+1370+250")
window.focus_set()
#截图
def cut():
global img
scrren_cut()
img = cv2.imread('screen.jpg')
cv2.namedWindow('image')
cv2.setMouseCallback('image', on_mouse)
cv2.imshow('image', img)
cv2.waitKey(0)
os.remove('screen.jpg')
def scrren_cut():
beg = time.time()
debug = False
# img = ImageGrab.grab(bbox=(250, 161, 1141, 610))
image = ImageGrab.grab()
image.save("screen.jpg")
# PIL image to OpenCV image
def on_mouse(event, x, y, flags, param):
global img, point1, point2
img2 = img.copy()
if event == cv2.EVENT_LBUTTONDOWN: #左鍵點擊
point1 = (x,y)
cv2.circle(img2, point1, 10, (0,255,0), 5)
cv2.imshow('image', img2)
elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON): #按住左鍵拖曳
cv2.rectangle(img2, point1, (x,y), (255,0,0), 5)
cv2.imshow('image', img2)
elif event == cv2.EVENT_LBUTTONUP: #左鍵放開
point2 = (x,y)
cv2.rectangle(img2, point1, point2, (0,0,255), 5)
cv2.imshow('image', img2)
min_x = min(point1[0],point2[0])
min_y = min(point1[1],point2[1])
width = abs(point1[0] - point2[0])
height = abs(point1[1] -point2[1])
cut_img = img[min_y:min_y+height, min_x:min_x+width]
cv2.imwrite('cut.bmp', cut_img)
aString=windll.user32.LoadImageW(0,"cut.bmp",win32con.IMAGE_BITMAP,0,0,win32con.LR_LOADFROMFILE)
print(aString)
if aString !=0: ## 寫入剪貼簿並關閉CV視窗
clip.OpenClipboard()
clip.EmptyClipboard()
clip.SetClipboardData(win32con.CF_BITMAP, aString)
clip.CloseClipboard()
cv2.destroyAllWindows()
window.bind("<F11>",lambda event:cut()) #F11截圖
window.mainloop()
沒有留言:
張貼留言