一 python 生成隨機字符串序列+ 寫入到圖片上
from PIL import Image,ImageDraw,ImageFont import numpy as np import random import string import cv2 # 生成隨機字符串 for i in range(1,10000): strnum = random.randint(2,10) ran_str = "".join(random.sample(string.ascii_letters + string.digits, strnum)) font = ImageFont.truetype('D:\Multimedia\RosewoodStd-Regular.otf', 60) # otf和ttf 是都可以使用。 image = Image.new("RGB", (300, 200), (255, 255, 255)) draw = ImageDraw.Draw(image) if strnum <=5:
# 參數一 寫入位置 參數二 文本 參數三 字體格式 fill 為文本顏色 默認為白色 draw.text((80, 80), ran_str, font=font, fill='Black') else: draw.text((20, 80), ran_str, font=font, fill='Black') path = "D:\AdobeVFR_release\\rosewood"+"\\rosewood_regular_"+str(i)+".jpeg" image.save(path) if(i%10==0): print("has already save %d images"%i)
疑問: 寫到圖片上的文本,怎么可以調整文本間間距 (論文模型需要)
二 使用cv2 一些圖像預處理函數
import cv2 from skimage import data_dir,io,color import numpy as np import random sigma = random.uniform(2.5,3.5)
# 高斯噪聲函數,這里寫的是按像素點單個處理,可以建一個高斯隨機數的矩陣 def GaussianNoise (img ,means =0,sigma =1.5): r = img[:,:,0].flatten() g = img[:,:,1].flatten() b = img[:,:,2].flatten() for i in range(img.shape[0]*img.shape[1]): r[i] = r[i]+random.gauss(0,sigma) g[i] = g[i]+random.gauss(0,sigma) b[i] = b[i]+random.gauss(0,sigma) img[:,:,0] = r.reshape([img.shape[0],img.shape[1]]) img[:,:,1] = r.reshape([img.shape[0],img.shape[1]]) img[:,:,2] = r.reshape([img.shape[0],img.shape[1]]) return img
# 幾何變化函數,主要功能是扭曲 def Geometric_changes(image,width,height): pts1 = np.float32([[50, 50], [200, 50], [50, 200]]) x = random.randint(50,100) y = random.randint(200,250) z = random.randint(10,50) pts2 = np.float32([[z, x], [200, 50], [x, y]]) M = cv2.getAffineTransform(pts1, pts2) image_0 = cv2.warpAffine(image, M, (width, height)) return image_0 path ='D:\AdobeVFR_release\sythetic' string = path+'/*.jpeg'
”“”
io.ImageCollrction 將圖片路徑整理成一個list
”“” coll = io.ImageCollection(string) a = np.array(coll) for i in range(95,len(a)): height = a[i].shape[0] width = a[i].shape[1] image_0 = GaussianNoise(a[i]) image_0 = cv2.GaussianBlur(image_0,(5,5),sigma) # 高斯模糊 image_0 = Geometric_changes(image_0, width, height)
# 縮放函數,fx,fy為縮放因子 interpolation有五種,
#INTER_AREA 基於局部像素的重采樣 圖像縮小時候,該方法可以避免波紋
#INTER_NEAREST 最近鄰插值法 適合放大
#INTER_LINEAR 雙線性插值法 默認
#INTER_CUBIC 基於4x4像素鄰域的3次插值法 適合放大
#INTER_LANCZOS4 - 基於8x8像素鄰域的Lanczos插值
image_0 = cv2.resize(image_0, None, fx=random.uniform(5 / 6, 7 / 6), fy=1, interpolation=cv2.INTER_AREA)
path = "D:\AdobeVFR_release\sydata"+"\d"+str(i)+".jpeg" cv2.imwrite(path, image_0) if(i%10==0): print("has already %d image" % i)
還有一些圖像處理函數 以后更新