Advertisement
Guest User

#1ZCSdU0U (Python)

a guest
Sep 26th, 2022
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.29 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. from pathlib import Path
  4.  
  5. import cv2
  6.  
  7. MINIMAL_SIZE = 400
  8. OUT_FOLDER = Path("test_cut_image/Output")
  9. IN_FOLDER = Path("test_cut_image/Input")
  10. FILENAME = "*.jpg"
  11. NUM_FILE = Path("test_cut_image/config/num.txt")
  12.  
  13. # ============================================================================
  14.  
  15.  
  16. def main() -> None:
  17.     OUT_FOLDER.mkdir(exist_ok=True)
  18.     pictures = sorted(IN_FOLDER.glob(FILENAME), key=lambda x: x.stem)
  19.     if not pictures:
  20.         print(f"No picture was found in {IN_FOLDER}")
  21.         return
  22.  
  23.     num_of_files = len(pictures)
  24.     for count, jpgfile in enumerate(pictures):
  25.         print("=======================================")
  26.         print(f"# Load {jpgfile.name} ({count+1}/{num_of_files})")
  27.  
  28.         # load jpg file and provess
  29.         image = cv2.imread(str(jpgfile))
  30.         original = image.copy()
  31.         gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  32.  
  33.         thresh = cv2.adaptiveThreshold(
  34.             gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 25, 2
  35.         )
  36.         kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
  37.         thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
  38.  
  39.         # load start number from config file
  40.         # ROI_number = int(NUM_FILE.read_text().strip("\n"))
  41.         ROI_number = 0
  42.  
  43.         # Find contours, obtain bounding box, extract and save ROI
  44.         cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  45.         cnts = cnts[0] if len(cnts) == 2 else cnts[1]
  46.         # get new image form jpg file
  47.         for c in cnts:
  48.             x, y, w, h = cv2.boundingRect(c)
  49.             # size must more then MINIMAL_SIZE x MINIMAL_SIZE
  50.             if w < MINIMAL_SIZE or h < MINIMAL_SIZE or w > 1500:
  51.                 continue
  52.  
  53.             image = cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 10)
  54.             ROI = original[y : y + h, x : x + w]
  55.  
  56.             newfile = OUT_FOLDER.joinpath(f"IMG_{ROI_number+1:0>5d}.jpg")
  57.             print(f"  Create => {newfile.name}")
  58.             # save new image to file
  59.             cv2.imwrite(str(newfile), ROI)
  60.             ROI_number += 1
  61.  
  62.         # save number of image start
  63.         NUM_FILE.write_text(f"{ROI_number:d}")
  64.  
  65.     print("# Finish")
  66.  
  67.  
  68. if __name__ == "__main__":
  69.     main()
  70.  
Tags: OpenCV
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement