import os
import cv2
import numpy as np
from random import randint
import matplotlib.pyplot as plt
def drawLine(img,cnt=50):
""" 随机划线\n
cnt: 默认画20条垂直线\n"""
# 生成一个随机位置
for i in range(cnt):
y1,x1 = randint(0,hight-1),randint(0,width-1)
up,down,left,right = [1,2,3,4]
direction = randint(1,5) # 方向
if direction==up or direction==down:
maxlen = hight # 最大长度
else:
maxlen = width # 最大长度
yindex, xindex = y1, x1
cnt = 0
if direction==up:
while yindex>0:
# 一直往上走,直到碰到0或者走完最大长度 (b g r)
if cnt>maxlen:
break
img[yindex, xindex, 0] = 0
img[yindex, xindex, 1] = 0
img[yindex, xindex, 2] = 0
yindex -=1 # y--,x不变
cnt +=1
elif direction == down:
while yindex<hight:
# 一直往下走,直到碰到height或者走完最大长度 (b g r)
if cnt>maxlen:
break
img[yindex, xindex, 0] = 0
img[yindex, xindex, 1] = 0
img[yindex, xindex, 2] = 0
yindex +=1 # y++,x不变
cnt +=1
elif direction == left:
while xindex>0:
# 一直往左走,直到碰到0或者走完最大长度 (b g r)
if cnt > maxlen:
break
img[yindex, xindex, 0] = 0
img[yindex, xindex, 1] = 0
img[yindex, xindex, 2] = 0
xindex -= 1 # x--,y不变
cnt += 1
else:
# 往右走
while xindex<width:
# 一直往右走,直到碰到width或者走完最大长度 (b g r)
if cnt > maxlen:
break
img[yindex, xindex, 0] = 0
img[yindex, xindex, 1] = 0
img[yindex, xindex, 2] = 0
xindex += 1 # x++,y不变
cnt += 1
return img
if __name__ == '__main__':
hight,width = 900,1800
imgor = np.ones((hight,width,3),dtype=np.uint8)*255 # 原始图像
imgtest = np.ones((hight,width,3),dtype=np.uint8)*127
saveDir = "imgs/"
if not os.path.exists(saveDir):
os.mkdir(saveDir) # 保存路径
num_img = 5 # 保存图像数量
for i in range(num_img):
mdfImg = drawLine(imgor.copy())
resutl = np.vstack((imgtest,mdfImg))
# cv2.namedWindow('result',cv2.WINDOW_NORMAL)
# cv2.imshow('lineimg',imgor)
# cv2.waitKey(0)
cv2.imwrite(saveDir+"lineimg_"+str(i+1)+".jpg",mdfImg)
""" subplot方法 """
# plt.subplot(1,2,1)
# plt.imshow(imgor)
# plt.xticks([])
# plt.yticks([])
# plt.title('original')
#
# plt.subplot(1, 2, 2)
# plt.imshow(mdfImg)
# plt.xticks([])
# plt.yticks([])
# plt.title('modified')
# plt.show()
""" subplot方法结束 """