Advertisement
creativesamurai1982

PJ01_Python_pyFrameCutter.py

Mar 6th, 2024
1,160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.88 KB | Software | 0 0
  1. import cv2
  2. import numpy as np
  3. import os
  4. import time
  5. from watchdog.observers import Observer
  6. from watchdog.events import FileSystemEventHandler
  7.  
  8. # Define the folder to monitor
  9. folder_to_monitor = 'C:\\Users\\david\\Desktop\\TESTING\\scans'
  10.  
  11. # Define the output folder
  12. output_folder = 'C:\\Users\\david\\Desktop\\TESTING\\output'
  13.  
  14. # Configure Settings
  15.  
  16.  
  17. # ThreshHold Settings
  18. thresholdValue = 205
  19. maxValue = 225
  20.  
  21. # Canny Edge Detection
  22. upper = 50
  23. lower = 150
  24.  
  25. # Create a class to handle file system events
  26. class ImageHandler(FileSystemEventHandler):
  27.     def on_created(self, event):
  28.         if event.is_directory:
  29.             return
  30.  
  31.         if event.src_path.endswith(('.jpg', '.png', '.jpeg')):
  32.             print(f"New image detected: {event.src_path}")
  33.             process_image(event.src_path)
  34.            
  35. # Initialize a counter for frame filenames
  36. frame_counter = 1
  37.  
  38. # Function to process an image
  39. def process_image(image_path):
  40.     # Declare frame_counter as global    
  41.     global frame_counter
  42.    
  43.     # Load the original image
  44.     original_image = cv2.imread(image_path)
  45.  
  46.     # Rotate the original image 180 degrees
  47.     rotated_image = cv2.rotate(original_image, cv2.ROTATE_180)
  48.  
  49.     # Convert to grayscale
  50.     grey = cv2.cvtColor(rotated_image, cv2.COLOR_BGR2GRAY)
  51.  
  52.     # Use threshold to convert image to binary
  53.     ret, thresh1 = cv2.threshold(grey, thresholdValue, maxValue, cv2.THRESH_BINARY) # 213
  54.  
  55.     # Apply morphological operations to remove specs or dirt/noise from the sprocket holes
  56.     kernel = np.ones((8, 8), np.uint8)
  57.     closing = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE, kernel, iterations=2)
  58.  
  59.     # Edge Detection for detecting contours
  60.     edge = cv2.Canny(closing, upper, lower, apertureSize=7, L2gradient=True)
  61.  
  62.     # Finding Contours
  63.     cnts, _ = cv2.findContours(edge, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  64.  
  65.     cnts = sorted(cnts, key=lambda x: cv2.boundingRect(x)[0])
  66.  
  67.     # Create a list to store the cropped ROIs
  68.     cropped_rotated_rois = []
  69.  
  70.     for c in cnts:
  71.         x, y, w, h = cv2.boundingRect(c)
  72.  
  73.         if h > 200 and w > 20:
  74.             # Adjust the coordinates to create a larger bounding box
  75.             x -= -50  # Move the left edge 10 pixels to the left
  76.             y -= 10  # Move the top edge 10 pixels up
  77.             w += 600  # Increase the width by 20 pixels
  78.             h += 1050  # Increase the height by 20 pixels
  79.  
  80.             # Crop the ROI from the original image
  81.             roi = rotated_image[y:y+h, x:x+w]
  82.  
  83.             # Rotate the cropped ROI (90 degrees clockwise)
  84.             rotated_roi = cv2.rotate(roi, cv2.ROTATE_90_CLOCKWISE)
  85.  
  86.             # Flip the rotated ROI vertically
  87.             flipped_roi = cv2.flip(rotated_roi, 1)
  88.  
  89.             # Append the rotated and flipped ROI to the list
  90.             cropped_rotated_rois.append(flipped_roi)
  91.  
  92.     # Discard the last ROI if there are more than one
  93.     if len(cropped_rotated_rois) > 1:
  94.         cropped_rotated_rois.pop()
  95.  
  96.     # Save each cropped ROI to the output folder
  97.     for idx, roi in enumerate(cropped_rotated_rois):
  98.         output_filename = f"frame{frame_counter:06}.jpg"
  99.         output_path = os.path.join(output_folder, output_filename)
  100.         cv2.imwrite(output_path, roi)
  101.         print(f"Processed image saved: {output_path}")
  102.        
  103.         # Increment the frame counter
  104.         frame_counter += 1
  105.  
  106. # Set up the watchdog observer
  107. event_handler = ImageHandler()
  108. observer = Observer()
  109. observer.schedule(event_handler, folder_to_monitor, recursive=False)
  110. observer.start()
  111.  
  112. print(f"Monitoring folder: {folder_to_monitor}")
  113. try:
  114.     while True:
  115.         time.sleep(1)
  116. except KeyboardInterrupt:
  117.     observer.stop()
  118.  
  119. observer.join()
  120.  
  121. # Call the process_image function for each image
  122. for image_filename in image_filenames:
  123.     image_path = os.path.join(input_folder, image_filename)
  124.     process_image(image_path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement