furas

cv2, tkinter, pillow - crop frame from camera

Jul 5th, 2020 (edited)
1,418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. # author: Bartlomiej "furas" Burek (https://blog.furas.pl)
  2. # date: 2020.07.06
  3. # https://stackoverflow.com/questions/62746177/crop-webcam-live-with-cv2-in-python
  4.  
  5. import tkinter as tk
  6. import cv2
  7. from PIL import Image, ImageTk
  8.  
  9. # --- functions ---
  10.  
  11. def show_frame():
  12.    
  13.     ret, frame = cap.read()
  14.    
  15.     if frame is not None:
  16.  
  17.         # crop numpy array
  18.         #frame = frame[0:900, 100:200]
  19.  
  20.         frame = cv2.flip(frame, 1)
  21.         frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
  22.        
  23.         image = Image.fromarray(frame)
  24.  
  25.         # OR crop PIL image      
  26.         image = image.crop((100, 0, 200, 900))
  27.  
  28.         photo = ImageTk.PhotoImage(image=image)
  29.         label_main.photo = photo
  30.         label_main.configure(image=photo)
  31.    
  32.     label_main.after(10, show_frame)
  33.  
  34. # --- main ---
  35.  
  36. #width  = 1000
  37. #height = 1000
  38.  
  39. cap = cv2.VideoCapture(0)
  40. #cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
  41. #cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
  42.  
  43. root = tk.Tk()
  44.  
  45. #width_px  = root.winfo_screenwidth()
  46. #height_px = root.winfo_screenheight()
  47.  
  48. #display = '{}x{}'.format(500, height_px)
  49. #root.geometry(display)
  50.  
  51. #root.configure(background='green')
  52.  
  53. root.bind('<Escape>', lambda event:root.destroy())
  54.  
  55. label_main = tk.Label(root)
  56. label_main.pack()
  57.  
  58. show_frame()
  59.  
  60. root.mainloop()
  61.  
  62. cap.release()
Add Comment
Please, Sign In to add comment