(
img,
targets=(),
degrees=10,
translate=0.1,
scale=0.1,
shear=10,
perspective=0.0,
border=(0, 0),
)
| 52 | |
| 53 | |
| 54 | def random_perspective( |
| 55 | img, |
| 56 | targets=(), |
| 57 | degrees=10, |
| 58 | translate=0.1, |
| 59 | scale=0.1, |
| 60 | shear=10, |
| 61 | perspective=0.0, |
| 62 | border=(0, 0), |
| 63 | ): |
| 64 | # targets = [cls, xyxy] |
| 65 | height = img.shape[0] + border[0] * 2 # shape(h,w,c) |
| 66 | width = img.shape[1] + border[1] * 2 |
| 67 | |
| 68 | # Center |
| 69 | C = np.eye(3) |
| 70 | C[0, 2] = -img.shape[1] / 2 # x translation (pixels) |
| 71 | C[1, 2] = -img.shape[0] / 2 # y translation (pixels) |
| 72 | |
| 73 | # Rotation and Scale |
| 74 | R = np.eye(3) |
| 75 | a = random.uniform(-degrees, degrees) |
| 76 | # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations |
| 77 | s = random.uniform(scale[0], scale[1]) |
| 78 | # s = 2 ** random.uniform(-scale, scale) |
| 79 | R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) |
| 80 | |
| 81 | # Shear |
| 82 | S = np.eye(3) |
| 83 | S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) |
| 84 | S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) |
| 85 | |
| 86 | # Translation |
| 87 | T = np.eye(3) |
| 88 | T[0, 2] = ( |
| 89 | random.uniform(0.5 - translate, 0.5 + translate) * width |
| 90 | ) # x translation (pixels) |
| 91 | T[1, 2] = ( |
| 92 | random.uniform(0.5 - translate, 0.5 + translate) * height |
| 93 | ) # y translation (pixels) |
| 94 | |
| 95 | # Combined rotation matrix |
| 96 | M = T @ S @ R @ C # order of operations (right to left) is IMPORTANT |
| 97 | |
| 98 | ########################### |
| 99 | # For Aug out of Mosaic |
| 100 | # s = 1. |
| 101 | # M = np.eye(3) |
| 102 | ########################### |
| 103 | |
| 104 | if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed |
| 105 | if perspective: |
| 106 | img = cv2.warpPerspective( |
| 107 | img, M, dsize=(width, height), borderValue=(114, 114, 114) |
| 108 | ) |
| 109 | else: # affine |
| 110 | img = cv2.warpAffine( |
| 111 | img, M[:2], dsize=(width, height), borderValue=(114, 114, 114) |
no test coverage detected