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)
裁剪图片代码
最新推荐文章于 2024-07-25 20:33:09 发布