python常用处理代码

前言

最近做深度学习项目,很多情况下都需要自己处理数据集,整理文件,记录文件关系,修改文件名字等等,做个记录。

文件夹下文件按顺序重命名

import os
# 重命名文件夹路径
path = "./dir/"

"""os.listdir(path) 操作效果为 返回指定路径(path)文件夹中所有文件名"""
filename_list = os.listdir(path)  # 扫描目标路径的文件,将文件名存入列表

for index,name in enumerate(filename_list):
    type = name.split(".")[-1]
    new_name = str(index) + "." + type
    os.rename(path + name, path + new_name)
    print("重命名第" + str(index) + "个文件")

主要函数:os.listdir(path)返回该路径下所有文件名字,列表类型。

目标检测根据boxes数创建VOC数据集xml文件

def write_xml(savedir, image, boxes,imgWidth = 1980, imgHeight = 1080,
              depth=3, pose="Unspecified"):
    if not os.path.exists(savedir):
        os.makedirs(savedir)
    currentfolder = savedir.split("\\")[-1]
    annotation = ET.Element("annotation")
    ET.SubElement(annotation, 'folder').text = str(currentfolder)
    ET.SubElement(annotation, 'filename').text = str(image)
    size = ET.SubElement(annotation, 'size')
    ET.SubElement(size, 'width').text = str(imgWidth)
    ET.SubElement(size, 'height').text = str(imgHeight)
    ET.SubElement(size, 'depth').text = str(depth)
    ET.SubElement(annotation, 'segmented').text = '0'
    for box in boxes:
        obj = ET.SubElement(annotation, 'object')
        ET.SubElement(obj, 'name').text = str(box[6])
        ET.SubElement(obj, 'pose').text = str(pose)
        ET.SubElement(obj, 'difficult').text = '0'

        bbox = ET.SubElement(obj, 'bndbox')
        ET.SubElement(bbox, 'xmin').text = str(box[0])
        ET.SubElement(bbox, 'ymin').text = str(box[1])
        ET.SubElement(bbox, 'xmax').text = str(box[0] + box[2])
        ET.SubElement(bbox, 'ymax').text = str(box[1] + box[3])

    xml_str = ET.tostring(annotation)
    root = etree.fromstring(xml_str)
    xml_str = etree.tostring(root, pretty_print=True)
    save_path = os.path.join(savedir, image.split(".")[-1] + ".xml")
    with open(save_path, 'wb') as temp_xml:
        temp_xml.write(xml_str)

这里传的boxes参数数目标检测框的列表,我这里用的格式是[[xmin,ymin,width,height,0,0,label],[xmin,ymin,width,height,0,0,label],[xmin,ymin,width,height,0,0,label] …],这两个0是我不记得是啥了,但是没用上就无所谓了。

视屏转图片

import cv2
import os
path = "../test_imgs/recordImgs/"
if not os.path.exists(path):
    os.mkdir(path)
cap = cv2.VideoCapture("../record.avi")  # 打开视频
frame = 0
while cap.isOpened():
    # 数据获取
    ret, fram = cap.read()
    cv2.imwrite(path + str(frame) + ".png",fram)
    frame+=1
    print("写入" + str(frame))
    if frame > 100:
        break

cap.release()

图片转视屏

import os
import cv2
import numpy as np

path = './result/'
filelist = os.listdir(path)

fps = 24 #视频每秒24帧
size = (640, 368) #需要转为视频的图片的尺寸
#可以使用cv2.resize()进行修改

video = cv2.VideoWriter("result.avi", cv2.VideoWriter_fourcc('I', '4', '2', '0'), fps, size)
#视频保存在当前目录下

for item in filelist:
    item = path + item
    img = cv2.imread(item)
    video.write(img)

video.release()
cv2.destroyAllWindows()

图片像素写入txt

import cv2

img = cv2.imread('../test_imgs/4.png' , cv2.IMREAD_GRAYSCALE)
print('图像的形状,返回一个图像的(行数,列数,通道数):', img.shape)
print('图像的像素数目:', img.size)
print('图像的数据类型:', img.dtype)
#img = cv2.resize(img,(280,280)) 可以改变图片的大小

fname = open('./xiangsu3.txt','w')
fname.write('图像的形状,返回一个图像的(行数,列数,通道数):'+str(img.shape)+'\n')
fname.write('图像的像素数目:'+str(img.size)+'\n') #----2
fname.write('图像的数据类型:'+str(img.dtype)+'\n') #----3
Xlenth = img.shape[1]#图片列数
Ylenth = img.shape[0]#图片行数
a = 1 #----4
for i in range(Ylenth):
    fname.write(str(a) + ":"+"\n")#----5
    for j in range(Xlenth):
        fname.write(str(img[i][j])+" ")
    a += 1#----6
    fname.write("\n")
fname.close()

cv2.imshow("image",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

文件夹不存在则创建

path = "../test_imgs/recordImgs/"
if not os.path.exists(path):
    os.mkdir(path)

猜你喜欢

转载自blog.csdn.net/qq_37668436/article/details/107511478
今日推荐