# import cv2
# import numpy as np
#
# def imshow_image(image):
# cv2.namedWindow('image',cv2.WINDOW_AUTOSIZE)
# cv2.imshow("image",image)
# cv2.waitKey()
# cv2.destroyAllWindows()
#
# def Crop_image(image):
# image=cv2.imread(image)
# if image is None:
# print('Unable to load image!')
# else:
# # print(image.shape)
# image_gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
# # print(image_gray.shape)
# # 最大类间方差法(大津算法),thresh会被忽略,自动计算一个阈值
# image_adaptive_threshold = cv2.adaptiveThreshold(image_gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,15,2)
# # image_adaptive_threshold = cv2.medianBlur(image_adaptive_threshold, 7)
# # 创建膨胀和腐蚀的结构元素
# kernel = np.ones((5, 5), np.uint8)
# # 对图像进行膨胀
# dilated_image = cv2.dilate(image_adaptive_threshold, kernel, iterations=1)
# # 创建一个与输入图像大小相同的遮罩
# image_fill = dilated_image.copy()
# # 定义填充起始点
# h,w=dilated_image.shape[:2]
# start_seed = (w//2, h//2)
# seed_pixel_value = dilated_image[start_seed[1], start_seed[0]]
# # 输出种子点的像素值
# print("Seed Pixel Value:", seed_pixel_value)
# # 如果起始点的像素值小于 255,将小于 255 的像素值都设置为 255
#
# if seed_pixel_value == 255:
# pass
# else:
# dilated_image[start_seed[1], start_seed[0]] = 255
# print("New pixel value at seed point:", dilated_image[start_seed[1], start_seed[0]])
#
# # imshow_image(image_fill)
# # 创建一个与输入图像大小相同的遮罩
# mask = np.zeros((dilated_image.shape[0] + 2, dilated_image.shape[1] + 2),
# dtype=np.uint8)
# # 定义填充的新像素值
# new_value = 255
# # 定义填充的连通区域的低、高像素差值范围
# lo_diff = 50
# hi_diff = 200
# # 执行泛洪填充
# cv2.floodFill(image_fill, mask, start_seed, new_value, (lo_diff, lo_diff, lo_diff),
# (hi_diff, hi_diff, hi_diff),
# flags=cv2.FLOODFILL_FIXED_RANGE)
#
# # imshow_image(image_fill)
#
# # 找到泛洪填充后的掩码中的最小矩形区域
# contours, _ = cv2.findContours(image_fill, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# if contours:
# # 获取最大的轮廓区域
# largest_contour = max(contours, key=cv2.contourArea)
# # 找到最大轮廓的边界框
# x, y, w, h = cv2.boundingRect(largest_contour)
#
# # 根据边界框剪切原始图像
# cropped_image = image[y:y + h, x:x + w]
#
# cv2.imwrite('crop_images',cropped_image)
#
#
# imgfile="D:\glioma_datasets\\20230719Slice\\36\\36_flair.nii2\\36_flair.nii2_020.jpg"
# Crop_image(imgfile)
import os
import cv2
import numpy as np
def crop_and_save_images(input_folder, output_folder):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
image_files = os.listdir(input_folder)
for image_file in image_files:
if image_file.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp')):
image_path = os.path.join(input_folder, image_file)
image = cv2.imread(image_path)
if image is not None:
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image_adaptive_threshold = cv2.adaptiveThreshold(image_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 15, 2)
kernel = np.ones((5, 5), np.uint8)
dilated_image = cv2.dilate(image_adaptive_threshold, kernel, iterations=1)
h, w = dilated_image.shape[:2]
start_seed = (w // 2, h // 2)
seed_pixel_value = dilated_image[start_seed[1], start_seed[0]]
if seed_pixel_value != 255:
dilated_image[start_seed[1], start_seed[0]] = 255
mask = np.zeros((dilated_image.shape[0] + 2, dilated_image.shape[1] + 2), dtype=np.uint8)
new_value = 255
lo_diff = 50
hi_diff = 200
cv2.floodFill(dilated_image, mask, start_seed, new_value, (lo_diff, lo_diff, lo_diff),
(hi_diff, hi_diff, hi_diff), flags=cv2.FLOODFILL_FIXED_RANGE)
contours, _ = cv2.findContours(dilated_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
largest_contour = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(largest_contour)
cropped_image = image[y:y + h, x:x + w]
output_path = os.path.join(output_folder, image_file)
cv2.imwrite(output_path, cropped_image)
else:
print(f"Unable to load image: {image_path}")
if __name__ == "__main__":
input_folder = "A" # Replace with your input folder
output_folder = "B" # Replace with your output folder
crop_and_save_images(input_folder, output_folder)