python+opencv 图像预处理

一 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:MultimediaRosewoodStd-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_releasesythetic' 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_releasesydata"+"d"+str(i)+".jpeg" cv2.imwrite(path, image_0) if(i%10==0): print("has already %d image" % i)

还有一些图像处理函数 以后更新

原文地址:https://www.cnblogs.com/jzcbest1016/p/7808375.html