裁剪图片代码

import numpy as np
import random
import os
import cv2

def random_crop_with_points(image, points):
    """随机裁剪图像,并计算points在裁剪后的图像中的位置.
    Args:
        image: 图像数组
        points: [(x, y), ...],原图像中的坐标点集合
    Return:
        new_img: 裁剪后的图像
        new_pts: [(x, y), ...],原图中的点在裁剪后的图中的位置
    """

    h, w = image.shape[: 2]
    points = np.array(points, np.int32)
    min_x, min_y, max_x, max_y = np.min(points[:, 0]), np.min(points[:, 1]), np.max(points[:, 0]), np.max(points[:, 1])

    t, b, lft, r = (random.randint(0,h//8),
                    random.randint(h//8 + 1, h) if h//8 + 1 < h else h//8 + 1,
                    random.randint(0, w//8),
                    random.randint(w//8 + 1, w) if w//8 + 1 < w else w//8 + 1)

    new_img = image[t: b, lft: r, :]

    new_pts = [[x - lft, y - t] for x, y in points]

    return new_img, new_pts

path = r'C:\examples\ultralytics\tests\imges'
for file in os.listdir(path):
    img = cv2.imread(os.path.join(path,file))
    H,W,_ = img.shape
    imglist = []
    Hlist = [0]
    Wlist = [0]
    if W < H:
        Wlist.append(W//3)
        for i in range(1,4):
            Hlist.append(int(H/4*i))
    else:
        Hlist.append(H // 3)
        for i in range(1, 4):
            Wlist.append(int(W / 4 * i))
    Wlist.append(W)
    Hlist.append(H)
    if W < H:
        for i in range(len(Wlist) - 1):
            for j in range(len(Hlist) - 1):
                patch = img[Hlist[j]:Hlist[j+1],Wlist[i]:Wlist[i+1]]
                cv2.imshow('',patch)
                cv2.waitKey()
    else:
        for i in range(len(Wlist) - 1):
            for j in range(len(Hlist) - 1):
                patch = img[Hlist[j]:Hlist[j+1],Wlist[i]:Wlist[i+1]]
                cv2.imshow('',patch)
                cv2.waitKey()
    # with open(os.path.join(r'C:\examples\ultralytics\tests\txt',file.replace('jpg','txt'))) as f:
    #     datas = f.readlines()
    #     for data in datas:
    #         data = data.strip().split(' ')
    #         cls = data[0]
    #         x = float(data[1]) * W
    #         y = float(data[2]) * H
    #         w = float(data[3]) * W
    #         h = float(data[4]) *H
    #         x1 = int(x - w / 2)
    #         y1 = int(y - h / 2)
    #         x2 = int(x1 + w)
    #         y2 = int(y1 + h)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值