refer to code
.
import os
import cv2
from tqdm import tqdm
import numpy as np
# Path to input and output directories
input_dir = './background'
output_dir = './background_canny'
# Create the output directory if it doesn't exist
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
# Loop over all files in the input directory
for filename in tqdm(os.listdir(input_dir)):
    if filename.endswith('.jpg') or filename.endswith('.png'):
        # Load the input image
        img = cv2.imread(os.path.join(input_dir, filename), cv2.IMREAD_GRAYSCALE)
        # Apply Canny edge detection algorithm
        edges = cv2.Canny(img, 100, 200)
        # Find and draw the contours of the edge map
        contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        contours_filtered = []
        threshold = int( min(0.1 * (img.shape[0]), 0.1 * (img.shape[1]) ) )
        for cnt in contours:
            if cv2.arcLength(cnt, True) >= threshold:
                contours_filtered.append(cnt)
        edges_contours = cv2.drawContours(np.zeros_like(img), contours_filtered, -1, 255, 1)
        # Invert the image (black to white, white to black)
        img_inv = cv2.bitwise_not(edges_contours)
        # Apply binary thresholding to the image
        thresh, img_binary = cv2.threshold(img_inv, 127, 255, cv2.THRESH_BINARY)
        # Save the result in the output directory with the same file name
        output_path = os.path.join(output_dir, filename)
        cv2.imwrite(output_path, img_binary)
..
Thank you.
ππ»♂️
www.marearts.com

No comments:
Post a Comment