圖像局部放大

import cv2
import numpy as np
from PIL import Image

def get_mask_image(mask, left_top, right_top, left_bottom, right_bottom):
    # 顯示anchor的圖像 順序必須爲左上,左下,右下,右上
    contours = np.array([[left_top, left_bottom, right_bottom, right_top]], dtype=np.int)
    # print(contours)
    """
    第一個參數是顯示在哪個圖像上;
    第二個參數是輪廓;
    第三個參數是指定繪製輪廓list中的哪條輪廓,如果是-1,則繪製其中的所有輪廓;
    第四個參數是繪製的顏色;
    第五個參數是線條的粗細
    """
    mask_image = cv2.drawContours(mask, contours, -1, (0, 0, 255), 2)  # 顏色:BGR
    # cv2.imshow('drawimg', mask_image)
    # cv2.waitKey(0)
    return mask_image

if __name__ == '__main__':
    image_path = "./1.png" # 加載某張圖像

    original_image = cv2.imread(image_path)
    # print(original_image.shape)
    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] # anchor左上角的座標
    right_top = [100,50] # anchor右上角的座標
    left_bottom = [50,100] # anchor左下角的座標
    right_bottom = [100,100] # anchor右下角的座標

    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] # 得到剪切後的圖像
    # print(crop_img.shape)
    # cv2.imshow('cuttimg', crop_img)
    # cv2.waitKey(0)

    img = Image.fromarray(crop_img)
    # 這裏如果沒有mask直接操作原圖,那麼剪切後的圖像會帶個藍框
    # 因爲上邊生成mask_image的時候顏色順序是BGR,但是這裏是RGB
    # img.show()

    img = img.resize((original_image_width, original_image_height))
    # img.show()

    # 給放大的圖加紅色框
    left_top = [0, 0]  # anchor左上角的座標
    right_top = [original_image_width, 0]  # anchor右上角的座標
    left_bottom = [0, original_image_height]  # anchor左下角的座標
    right_bottom = [original_image_width, original_image_height]  # anchor右下角的座標
    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)

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章