龙空技术网

python剪切图片

编程吧 349

前言:

眼前姐妹们对“python剪切”都比较看重,朋友们都需要剖析一些“python剪切”的相关资讯。那么小编在网摘上搜集了一些有关“python剪切””的相关文章,希望各位老铁们能喜欢,兄弟们快快来学习一下吧!

1、有时候业务需要对图片中的固定位置区域进行剪切,通过cv2能够方便的进行剪切

例如下图,我们要剪切图中印章。首先要定位印章位置,可以参考工具“PPOCRLabelv2”进行标注,地址:PaddleOCR/README_ch.md at release/2.6 · PaddlePaddle/PaddleOCR · GitHub,例如下图中,左1的印章位置为[[323, 609],[489, 609], [489, 774], [323, 774]]

seal.png

下面用python+cv2对图片进行剪切

import cv2import osimport numpy as npdef get_rotate_crop_image(img, points):    '''    img_height, img_width = img.shape[0:2]    left = int(np.min(points[:, 0]))    right = int(np.max(points[:, 0]))    top = int(np.min(points[:, 1]))    bottom = int(np.max(points[:, 1]))    img_crop = img[top:bottom, left:right, :].copy()    points[:, 0] = points[:, 0] - left    points[:, 1] = points[:, 1] - top    '''    # assert len(points) == 4, "shape of points must be 4*2"    print(points)    points = np.float32(points)    print(points)    print(points[0],points[1])    img_crop_width = int(        max(        np.linalg.norm(points[0] - points[1]),        np.linalg.norm(points[2] - points[3])))    print("img_crop_width=",img_crop_width)    img_crop_height = int(        max(        np.linalg.norm(points[0] - points[3]),        np.linalg.norm(points[1] - points[2])))    print("img_crop_height=",img_crop_height)    pts_std = np.float32([[0, 0], [img_crop_width, 0],        [img_crop_width, img_crop_height],        [0, img_crop_height]])    M = cv2.getPerspectiveTransform(points, pts_std)    dst_img = cv2.warpPerspective(        img,        M, (img_crop_width, img_crop_height),        borderMode=cv2.BORDER_REPLICATE,        flags=cv2.INTER_CUBIC)    dst_img_height, dst_img_width = dst_img.shape[0:2]    if dst_img_height * 1.0 / dst_img_width >= 1.5:        dst_img = np.rot90(dst_img)    return dst_imgif __name__ == '__main__':    save_dir = "save_dir"    idx = 1    src_im = cv2.imread("./seal.png")    # seal_box = anno['seal_box']    txt_boxes = [[323, 609],[489, 609], [489, 774], [323, 774]]    crop_im = get_rotate_crop_image(src_im, txt_boxes)    save_path = os.path.join(save_dir, f'{idx}.png')    if not os.path.exists(save_dir):        os.makedirs(save_dir)    # print(src_im.shape)    cv2.imwrite(save_path, crop_im)

最终效果

标签: #python剪切