作业16:
只在一幅图中选定目标框,然后在目标周围生成随机框,并保存
import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
import numpy as np
import cv2 as cv
import random
Tomylove1 = mpimg.imread('pig.jpg') # 读取和代码处于同一目录下的 lena.png
# 此时 lena 就已经是一个 np.array 了,可以对它进行任意处理
Tomylove1.shape #(512, 512, 3)
image = cv.imread('pig.jpg')
r = cv.selectROI(image)
imCrop = image[int(r[1]):int(r[1] + r[3]), int(r[0]):int(r[0] + r[2])]#这里才是真正的左X左Y,右X右Y呢
cv.imshow('cut ', imCrop)
cv.rectangle(image, r, (55, 255, 155), 5)
#cv.rectangle(image, (168, 208), (227, 58), (0, 255, 0), 2)
cv.imshow('pig1.jpg', image)
for i in range(0,10):
x=r[0]+r[2]//2#r中的元素一定要分清楚Imcrop里谁是左X谁是右X谁是左Y谁是右,按这个对照imCrop = frame[right_y_down:left_y_up, left_x_up:right_x_down, :]
y=r[1]+r[3]//2#//为python整除
left_x_up = x-random.randint(0,100)
left_y_up = y+random.randint(0,100)#注意这里的调参
right_x_down = x + random.randint(0,100)
right_y_down = y- random.randint(0,100)
cv.rectangle(image, (left_x_up, left_y_up), (right_x_down, right_y_down), (55, 255, 155), 5)
res = cv.resize(imCrop, (32, 32), interpolation=cv.INTER_CUBIC)
imCrop = image[right_y_down:left_y_up, left_x_up:right_x_down, :]
cv.imwrite('pigy' + str(i) + '.jpg', res)
i +=1
cv.imshow('angle', image) # 带有目标框的视频
#res = cv.resize(imCrop, (32, 32), interpolation=cv.INTER_CUBIC)
#cv.imwrite('pigy' + str(i) + '.jpg', res)
plt.imshow(Tomylove1) # 显示图片
plt.axis('off') # 不显示坐标轴
plt.show()