from PIL import Image import cv2 import numpy as np def crop1(image_path, mask_path): # 读取图像和mask文件 image = Image.open(image_path).convert("RGB") mask = Image.open(mask_path) # 确保图片和mask有相同的尺寸 #assert image.size == mask.size # 将mask转换为二值图像 mask = mask.convert('1') # 使用mask获取感兴趣的区域 image = np.array(image) mask = np.array(mask) region_of_interest = image * mask[:, :, None] image=Image.fromarray(region_of_interest) return image def crop2(image_path, mask_path): # 读取图像和mask image = Image.open(image_path).convert("RGBA") mask = Image.open(mask_path).convert('L') print(mask.size) # 确保图像和mask的大小相同 assert image.size == mask.size, "图像和mask的大小必须相同" # 将图像和mask转换为numpy数组 image_array = np.array(image) mask_array = np.array(mask) #mask_array[mask_array != 0] = 255 # # print(sum(mask_array)) # 创建一个新的透明度通道,对应mask为0的区域为透明 alpha_channel = np.ones(mask_array.shape[:2], dtype=np.uint8) * 255 print(mask_array.shape) alpha_channel[mask_array==0] = 0 #mask2=Image.fromarray(alpha_channel) # print(mask_array) # print(alpha_channel) # 将新的透明度通道添加到图像中 image_array[..., 3] = alpha_channel # 将结果数组转换回Image对象 result_image = Image.fromarray(image_array) # 保存结果图像为PNG格式 return result_image def crop3(image_path, mask_path): # 读取图像和mask image = cv2.imread(image_path) if isinstance(mask_path, str): mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) else: mask = np.ones((512, 512), dtype=np.uint8) # 计算mask的外接矩形 # 计算mask的所有外接矩形 contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) min_x, min_y, max_x, max_y = None, None, None, None for contour in contours: x, y, w, h = cv2.boundingRect(contour) if min_x is None or x < min_x: min_x = x if min_y is None or y < min_y: min_y = y if max_x is None or x + w > max_x: max_x = x + w if max_y is None or y + h > max_y: max_y = y + h # 只保留原图对应的外接矩形的部分 result = image[min_y:max_y, min_x:max_x] result=Image.fromarray(result) width, height = result.size if width < height: new_size = (224, int(height * 224 / width)) else: new_size = (int(width * 224 / height), 224) # 将短边等比缩放到224 result = result.resize(new_size, Image.Resampling.LANCZOS) return result # 使用方法 #get_bounding_box('your_image.png', 'your_mask.png') # def crop4(image_path, mask_path): # 读取图像和mask image = cv2.imread(image_path) mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) # 使用mask将对应图像mask=0的部分变黑 image = image * np.stack([mask]*3, axis=-1) # 计算mask的外接矩形 contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) min_x, min_y, max_x, max_y = None, None, None, None for contour in contours: x, y, w, h = cv2.boundingRect(contour) if min_x is None or x < min_x: min_x = x if min_y is None or y < min_y: min_y = y if max_x is None or x + w > max_x: max_x = x + w if max_y is None or y + h > max_y: max_y = y + h # 只保留原图对应的外接矩形的部分 result = image[min_y:max_y, min_x:max_x] result = Image.fromarray(result) return result