Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- from pathlib import Path
- import cv2
- MINIMAL_SIZE = 400
- OUT_FOLDER = Path("test_cut_image/Output")
- IN_FOLDER = Path("test_cut_image/Input")
- FILENAME = "*.jpg"
- NUM_FILE = Path("test_cut_image/config/num.txt")
- # ============================================================================
- def main() -> None:
- OUT_FOLDER.mkdir(exist_ok=True)
- pictures = sorted(IN_FOLDER.glob(FILENAME), key=lambda x: x.stem)
- if not pictures:
- print(f"No picture was found in {IN_FOLDER}")
- return
- num_of_files = len(pictures)
- for count, jpgfile in enumerate(pictures):
- print("=======================================")
- print(f"# Load {jpgfile.name} ({count+1}/{num_of_files})")
- # load jpg file and provess
- image = cv2.imread(str(jpgfile))
- original = image.copy()
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- thresh = cv2.adaptiveThreshold(
- gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 25, 2
- )
- kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7))
- thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
- # load start number from config file
- # ROI_number = int(NUM_FILE.read_text().strip("\n"))
- ROI_number = 0
- # Find contours, obtain bounding box, extract and save ROI
- cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- cnts = cnts[0] if len(cnts) == 2 else cnts[1]
- # get new image form jpg file
- for c in cnts:
- x, y, w, h = cv2.boundingRect(c)
- # size must more then MINIMAL_SIZE x MINIMAL_SIZE
- if w < MINIMAL_SIZE or h < MINIMAL_SIZE or w > 1500:
- continue
- image = cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 10)
- ROI = original[y : y + h, x : x + w]
- newfile = OUT_FOLDER.joinpath(f"IMG_{ROI_number+1:0>5d}.jpg")
- print(f" Create => {newfile.name}")
- # save new image to file
- cv2.imwrite(str(newfile), ROI)
- ROI_number += 1
- # save number of image start
- NUM_FILE.write_text(f"{ROI_number:d}")
- print("# Finish")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement