都是自己制作训练样本到处搜刮的小代码(有的记不住是哪里找的了),整理到一起方便找【狗头】
1. 图像格式转换png转jpg
from PIL import Image
import os
# 需要转换的图片所在的文件夹路径
folder_path = '***********'
# 需要保存图片的位置路径
save_path = '*************'
# 遍历文件夹中的所有文件
for file in os.listdir(folder_path):
# 如果文件是 PNG 格式的
if file.endswith('.png'):
# 打开文件
img = Image.open(os.path.join(folder_path, file))
# 获取文件名(不包含扩展名)
file_name = os.path.splitext(file)[0]
# 保存为 JPG 格式
img.save(os.path.join(save_path, file_name + '.jpg'))
2. 图像格式转换tiff转jpg
注:会降低tif质量,有损耗
import os, sys
import cv2
import numpy as np
from skimage import io # 使用IO库读取tif图片
# **********注:路径中不能含有中文,会转化失败*************
def tif_jpg_transform(file_path_name, bgr_savepath_name):
img = io.imread(file_path_name) # 读取文件名
img = img / img.max() # 使其所有值不大于一
img = img * 255 - 0.001 # 减去0.001防止变成负整型
img = img.astype(np.uint8) # 强制转换成8位整型
# img = np.array([img,img,img])
# img = img.transpose(1,2,0)
print(img.shape) # 显示图片大小和深度
b = img[:, :, 0] # 读取蓝通道
g = img[:, :, 1] # 读取绿通道
r = img[:, :, 2] # 读取红通道
bgr = cv2.merge([r, g, b]) # 通道拼接
cv2.imwrite(bgr_savepath_name, bgr) # 图片存储
tif_file_path = r'F:\TIF' # 为tif图片的文件夹路径
tif_fileList = os.listdir(tif_file_path)
for tif_file in tif_fileList:
file_path_name = tif_file_path + '/' + tif_file
jpg_path = r'F:\JPG' + '/' + tif_file.split('.')[0] + '.jpg' # .jpg图片的保存路径
print(jpg_path)
tif_jpg_transform(file_path_name, jpg_path)
3. 重命名文件夹下的文件
# coding = 'utf-8'
import os
def rename(path):
i = 0
'该文件夹下所有的文件(包括文件夹)'
FileList = os.listdir(path)
'遍历所有文件'
for files in FileList:
'原来的文件路径'
oldDirPath = os.path.join(path, files)
'如果是文件夹则递归调用'
if os.path.isdir(oldDirPath):
rename(oldDirPath)
'文件名'
fileName = os.path.splitext(files)[0]
'文件扩展名'
fileType = os.path.splitext(files)[1]
'新的文件路径'
newDirPath = os.path.join(path, str(i) + fileType)
'重命名'
os.rename(oldDirPath, newDirPath)
i += 1
path = r'**************'
rename(path)
4. 图像切割成固定大小
# coding=utf-8
import cv2
import numpy
import scipy.io as scio
import math
import os
imgFile = r'*********' # 待裁剪的图片
H = 640 # 裁剪大小
list_img = []
for root, _, fnames in sorted(os.walk(imgFile)):
for fname in fnames:
path = os.path.join(root, fname)
list_img.append(path)
for i in range(len(list_img)):
p, n = os.path.split(list_img[i])
pro, ext = os.path.splitext(n)
print(pro)
img = cv2.imread(list_img[i])
(h, w, c) = img.shape
h_n = math.ceil(h / H) # 裁剪的高
w_n = math.ceil(w / H) # 裁剪的宽
# (h, w, c) = img.shape
for i in range(h_n):
if i < h_n - 1:
for j in range(w_n):
if j < w_n - 1:
img_patch = img[i * H:(i + 1) * H, j * H:(j + 1) * H, :]
img_pathname = os.path.join(r"*******",
pro[:4] + '-' + str(i) + '-' + str(j) + '.png')
cv2.imwrite(img_pathname, img_patch)
else:
img_patch = img[i * H:(i + 1) * H, (w - H):, :]
img_pathname = os.path.join(r"*******",
pro[:4] + '-' + str(i) + '-' + str(j) + '.png')
cv2.imwrite(img_pathname, img_patch)
else:
for j in range(w_n):
if j < w_n - 1:
img_patch = img[(h - H):, j * H:(j + 1) * H, :]
img_pathname = os.path.join(r"*******",
pro[:4] + '-' + str(i) + '-' + str(j) + '.png')
cv2.imwrite(img_pathname, img_patch)
else:
img_patch = img[(h - H):, (w - H):, :]
img_pathname = os.path.join(r"*******",
pro[:4] + '-' + str(i) + '-' + str(j) + '.png')
cv2.imwrite(img_pathname, img_patch)
5. 样本随机抽稀
import os
import shutil
import random
def random_select_images(src_folder, dst_folder, num_images=1500):
# 获取所有的jpg文件路径
all_jpgs = []
for subdir, _, files in os.walk(src_folder):
for file in files:
if file.lower().endswith('.jpg'):
all_jpgs.append(os.path.join(subdir, file))
# 确保要抽取的图片数量不超过总数
num_images = min(num_images, len(all_jpgs))
# 随机选择图片
selected_images = random.sample(all_jpgs, num_images)
# 如果目标文件夹不存在,则创建
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
# 将选择的图片复制到目标文件夹
for image_path in selected_images:
dst_path = os.path.join(dst_folder, os.path.basename(image_path))
shutil.copy(image_path, dst_path)
print(f"Copied {num_images} images to {dst_folder}")
# 使用示例
src_folder = r"******************" # 替换为你的源文件夹路径
dst_folder = r"******************" # 替换为你的目标文件夹路径
random_select_images(src_folder, dst_folder)