图像随机裁剪三角形
import cv2
import numpy as np
import random
def cut_triangle(img):
height, width, _ = img.shape
corners = [(0, 0), (0, height - 1), (width - 1, 0), (width - 1, height - 1)]
chosen_corner = random.choice(corners)
# 随机生成三角形的其他两个顶点
if chosen_corner in [(0, 0), (width - 1, height - 1)]:
# 对角线为三角形的一边
point2 = (random.randint(0, width - 1), chosen_corner[1])
point3 = (chosen_corner[0], random.randint(0, height - 1))
else:
# 对角线为三角形的一边
point2 = (random.randint(0, width - 1), chosen_corner[1])
point3 = (chosen_corner[0], random.randint(0, height - 1))
# 创建一个mask,并绘制三角形
mask = np.zeros((height, width), dtype=np.uint8)
triangle_cnt = np.array([chosen_corner, point2, point3])
cv2.drawContours(mask, [triangle_cnt], 0, (255), -1)
# 应用mask(使用黑色填充三角形)
img[mask == 255] = (0, 0, 0)
# 显示和保存结果
cv2.imshow('Triangle Cut Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# cv2.imwrite('cut_image.jpg', img)
if __name__ == '__main__':
image_path = r'C:\Users\binjiling_c\1115\0_8000_0\15185527_297.jpg'
for i in range(50):
img = cv2.imread(image_path)
cut_triangle(img)