import cv2
import numpy as np
from PIL import Image
def get_mask_image(mask, left_top, right_top, left_bottom, right_bottom):
contours = np.array([[left_top, left_bottom, right_bottom, right_top]], dtype=np.int)
"""
第一个参数是显示在哪个图像上;
第二个参数是轮廓;
第三个参数是指定绘制轮廓list中的哪条轮廓,如果是-1,则绘制其中的所有轮廓;
第四个参数是绘制的颜色;
第五个参数是线条的粗细
"""
mask_image = cv2.drawContours(mask, contours, -1, (0, 0, 255), 2)
return mask_image
if __name__ == '__main__':
image_path = "./1.png"
original_image = cv2.imread(image_path)
original_image_width = original_image.shape[1]
original_image_height = original_image.shape[0]
print("该图像尺寸(宽*高)为:{}*{}".format(original_image_width, original_image_height))
left_top = [50,50]
right_top = [100,50]
left_bottom = [50,100]
right_bottom = [100,100]
mask = original_image.copy()
mask_image = get_mask_image(mask, left_top, right_top, left_bottom, right_bottom)
x1 = min(left_top[0], right_top[0], left_bottom[0], right_bottom[0])
x2 = max(left_top[0], right_top[0], left_bottom[0], right_bottom[0])
y1 = min(left_top[1], right_top[1], left_bottom[1], right_bottom[1])
y2 = max(left_top[1], right_top[1], left_bottom[1], right_bottom[1])
hight = y2 - y1
width = x2 - x1
crop_img = original_image[y1:y1 + hight, x1:x1 + width]
img = Image.fromarray(crop_img)
img = img.resize((original_image_width, original_image_height))
left_top = [0, 0]
right_top = [original_image_width, 0]
left_bottom = [0, original_image_height]
right_bottom = [original_image_width, original_image_height]
img = np.array(img)
mask_crop_img = get_mask_image(img, left_top, right_top, left_bottom, right_bottom)
result_img = np.vstack((mask_image, mask_crop_img))
cv2.imwrite("./result.jpg", result_img)