YuXin_Liu/丝束检测/edgeDetect.py

78 lines
2.7 KiB
Python

import os
import cv2
import numpy as np
def detect_edges(image_path, low_threshold, high_threshold):
"""使用 Canny 算法进行边缘检测"""
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
raise ValueError(f"Failed to load image from {image_path}")
blurred_image = cv2.GaussianBlur(image, (5, 5), 0)
edges = cv2.Canny(blurred_image, low_threshold, high_threshold)
return edges
def find_edge_bounds(edges):
"""找到边缘检测结果中的最远边界"""
# 获取所有边缘点的坐标
y_coords, x_coords = np.nonzero(edges)
if len(x_coords) == 0 or len(y_coords) == 0:
return None # 如果没有检测到边缘,返回 None
# 计算边缘点的最小和最大坐标
min_x = np.min(x_coords)
max_x = np.max(x_coords)
min_y = np.min(y_coords)
max_y = np.max(y_coords)
return min_x, max_x, min_y, max_y
def crop_image(image, min_x, max_x, min_y, max_y):
"""从图像中截取指定区域"""
return image[min_y:max_y, min_x:max_x]
def process_image(image_path, output_path, low_threshold, high_threshold):
"""处理单张图像,进行边缘检测并截取指定区域"""
edges = detect_edges(image_path, low_threshold, high_threshold)
image = cv2.imread(image_path)
if image is None:
raise ValueError(f"Failed to load image from {image_path}")
bounds = find_edge_bounds(edges)
if bounds is None:
print(f"No edges detected in {image_path}")
return
min_x, max_x, min_y, max_y = bounds
cropped_image = crop_image(image, min_x, max_x, min_y, max_y)
cv2.imwrite(output_path, cropped_image)
print(f"Saved cropped image to {output_path}")
def process_images_in_folder(input_folder, output_folder, low_threshold, high_threshold):
"""处理文件夹中的所有图像文件,进行边缘检测并截取指定区域"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
image_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename)
process_image(image_path, output_path, low_threshold, high_threshold)
# 设置参数
input_folder = r'/mnt/d/slikDetect/datasets/AlreadyCheckOnlyTiaoJuan/OnlyTiaoJuanImages/' # 输入文件夹路径
output_folder = 'edge_cut_original' # 输出文件夹路径
low_threshold = 50 # Canny 边缘检测的低阈值
high_threshold = 150 # Canny 边缘检测的高阈值
# 处理文件夹中的所有图像
process_images_in_folder(input_folder, output_folder, low_threshold, high_threshold)