图像预处理(图像非形变操作和图像归一化)"/>
Python 图像预处理(图像非形变操作和图像归一化)
图片来自网上截取,如有侵权,请联系我删除!!!
(一)图像非形变操作
>>>>>>Python代码:
import os
import cv2
import numpy as np
import time
# 非形变图像处理函数
def letterbox(img,height = 416,augment = False, color = (127.5,127.5,127.5)):# Resize a rectangular image to a padded squareshape = img.shape[:2] # shape = [height,width]ratio = float(height) / max(shape) # ratio = old / new 得到缩放比例new_shape = (round(shape[1] * ratio),round(shape[0] * ratio))dw = (height - new_shape[0]) / 2 # width paddingdh = (height - new_shape[1]) / 2 # height paddingtop,bottom = round(dh - 0.1),round(dh + 0.1)left,right = round(dw - 0.1),round(dw + 0.1)# resize imgif augment: # 数据增强interpolation = np.random.choice([None,cv2.INTER_NEAREST,cv2.INTER_LINEAR,None,cv2.INTER_NEAREST,cv2.INTER_LINEAR,cv2.INTER_AREA,cv2.INTER_CUBIC,cv2.INTER_LANCZOS4])if interpolation is None:img = cv2.resize(img,new_shape)else:img = cv2.resize(img,new_shape,interpolation = interpolation)else:img = cv2.resize(img,new_shape,interpolation=cv2.INTER_NEAREST)# print("resize time:",time.time()-s1)img = cv2.copyMakeBorder(img,top,bottom,left,right,cv2.BORDER_CONSTANT,value = color) # padded squarereturn img,ratio,dw,dhif __name__ == '__main__':path = './images/' # 图片路径img_size = 416 # 生成非形变图像的最终的尺寸,长和宽都是相等的for f_ in os.listdir(path):# 遍历文件夹中的图片img_o = cv2.imread(path+f_) # 加载图片文件img,_,_,_ = letterbox(img_o,height=img_size) # 非形变图像处理print("------------------->>>>")print("img_o shape:",img_o.shape)print("img shape:",img.shape)cv2.namedWindow("img_o",0) # 图像窗口的申明,参数: 窗口的尺寸可以通过鼠标去拉取改变,参数1:则固定为原尺寸,不可改变cv2.imshow("img_o",img_o)cv2.namedWindow("img",0)cv2.imshow("img",img)cv2.waitKey(0)
实验效果:
原图 补边图
原图 补边图
(二)图像归一化:
img = img/255.
如果您喜欢我的分享,就点个赞👍+收藏,这也是我努力更新文章的动力!!!!!
更多推荐
Python 图像预处理(图像非形变操作和图像归一化)
发布评论