有时会写很多脚本,临时使用以下过一段时间就忘得差不多了,但突然又用到了,你找之前写的找还找不到,就很气人...... 索性记录一下(不定时更新)。
Python:
清华源:pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/
1、文件分类:
import os
import shutil
root =r"G:\my\fire_data\img" #需要分离的文件,即image 与txt在此文件下
image =r"G:\my\fire_data\images"
label =r"G:\my\fire_data\label"
for x in os.scandir(root):
if x.name.endswith(".txt"): #获取路径
needpath =r"G:\my\fire_data\img\{name}".format(name=x.name)
print(needpath)
shutil.move(needpath,label) #将选中的文件移动到其它文件夹
if x.name.endswith(".jpg"):
needpath = r"G:\my\fire_data\img\{name}".format(name=x.name)
shutil.move(needpath,image)
#根据自己的需求进行更改
这个是运用python标准库shutil:
Python模块——shutil模块详解_数据分析与统计学之美-CSDN博客_python shutil
2、txt文件转换为xml文件
import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement
from PIL import Image
class Xml_make(object):
def __init__(self):
super().__init__()
def __indent(self, elem, level=0):
i = "\n" + level * "\t"
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + "\t"
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
self.__indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def _imageinfo(self, list_top):
annotation_root = ET.Element('annotation')
annotation_root.set('verified', 'no')
tree = ET.ElementTree(annotation_root)
'''
0:xml_savepath 1:folder,2:filename,3:path
4:checked,5:width,6:height,7:depth
'''
folder_element = ET.Element('folder')
folder_element.text = list_top[1]
annotation_root.append(folder_element)
filename_element = ET.Element('filename')
filename_element.text = list_top[2]
annotation_root.append(filename_element)
path_element = ET.Element('path')
path_element.text = list_top[3]
annotation_root.append(path_element)
checked_element = ET.Element('checked')
checked_element.text = list_top[4]
annotation_root.append(checked_element)
source_element = ET.Element('source')
database_element = SubElement(source_element, 'database')
database_element.text = 'Unknown'
annotation_root.append(source_element)
size_element = ET.Element('size')
width_element = SubElement(size_element, 'width')
width_element.text = str(list_top[5])
height_element = SubElement(size_element, 'height')
height_element.text = str(list_top[6])
depth_element = SubElement(size_element, 'depth')
depth_element.text = str(list_top[7])
annotation_root.append(size_element)
segmented_person_element = ET.Element('segmented')
segmented_person_element.text = '0'
annotation_root.append(segmented_person_element)
return tree, annotation_root
def _bndbox(self, annotation_root, list_bndbox):
for i in range(0, len(list_bndbox), 9):
object_element = ET.Element('object')
name_element = SubElement(object_element, 'name')
name_element.text = list_bndbox[i]
flag_element = SubElement(object_element, 'flag')
flag_element.text = list_bndbox[i + 1]
pose_element = SubElement(object_element, 'pose')
pose_element.text = list_bndbox[i + 2]
truncated_element = SubElement(object_element, 'truncated')
truncated_element.text = list_bndbox[i + 3]
difficult_element = SubElement(object_element, 'difficult')
difficult_element.text = list_bndbox[i + 4]
bndbox_element = SubElement(object_element, 'bndbox')
xmin_element = SubElement(bndbox_element, 'xmin')
xmin_element.text = str(list_bndbox[i + 5])
ymin_element = SubElement(bndbox_element, 'ymin')
ymin_element.text = str(list_bndbox[i + 6])
xmax_element = SubElement(bndbox_element, 'xmax')
xmax_element.text = str(list_bndbox[i + 7])
ymax_element = SubElement(bndbox_element, 'ymax')
ymax_element.text = str(list_bndbox[i + 8])
annotation_root.append(object_element)
return annotation_root
def txt_to_xml(self, list_top, list_bndbox):
tree, annotation_root = self._imageinfo(list_top)
annotation_root = self._bndbox(annotation_root, list_bndbox)
self.__indent(annotation_root)
tree.write(list_top[0], encoding='utf-8', xml_declaration=True)
def txt_2_xml(source_path, xml_save_dir, txt_dir):
COUNT = 0
for folder_path_tuple, folder_name_list, file_name_list in os.walk(source_path):
for file_name in file_name_list:
file_suffix = os.path.splitext(file_name)[-1]
if file_suffix != '.jpg':
continue
list_top = []
list_bndbox = []
path = os.path.join(folder_path_tuple, file_name)
xml_save_path = os.path.join(xml_save_dir, file_name.replace(file_suffix, '.xml'))
txt_path = os.path.join(txt_dir, file_name.replace(file_suffix, '.txt'))
filename = os.path.splitext(file_name)[0]
checked = 'NO'
im = Image.open(path)
im_w = im.size[0]
im_h = im.size[1]
width = str(im_w)
height = str(im_h)
depth = '3'
flag = 'rectangle'
pose = 'Unspecified'
truncated = '0'
difficult = '0'
list_top.extend([xml_save_path, folder_path_tuple, filename, path, checked,
width, height, depth])
for line in open(txt_path, 'r'):
line = line.strip()
info = line.split(' ') #info为读取txt文件的内容
print("info",info)
name = info[0] # 是类别信息根据自己的需求进行更改
if name == "0":
name = "person"
elif name =="1":
name = "car"
x_cen = float(info[1]) * im_w
y_cen = float(info[2]) * im_h
w = float(info[3]) * im_w
h = float(info[4]) * im_h
xmin = int(x_cen - w / 2)
ymin = int(y_cen - h / 2)
xmax = int(x_cen + w / 2)
ymax = int(y_cen + h / 2)
list_bndbox.extend([name, flag, pose, truncated, difficult,
str(xmin), str(ymin), str(xmax), str(ymax)])
Xml_make().txt_to_xml(list_top, list_bndbox)
COUNT += 1
print(COUNT, xml_save_path)
if __name__ == '__main__': #图片和txt放入到不同文件夹
source_path = r"H:\pytorch\yolov4-pytorch-master\output\img" # txt标注文件所对应的的图片
xml_save_dir = r"H:\pytorch\yolov4-pytorch-master\output\xml" # 转换为xml标注文件的保存路径
txt_dir = r"H:\pytorch\yolov4-pytorch-master\output\txt" # 需要转换的txt标注文件
txt_2_xml(source_path, xml_save_dir, txt_dir)
3、将视频每一帧保存为图片
import cv2 as cv
if __name__ == '__main__':
savepath = "img/" #图片保存路径
filename = "2.mp4"#读取视频
vc = cv.VideoCapture(filename)
if vc.isOpened(): #判断视频是否正常读取
# ret, frame 是 read 方法的两个返回值
#读取成功 ret为true 失败为false frame是获取的视频帧
ret,fream = vc.read()
else:
ret = False
a = 0
while ret:
a +=1
ret, fream = vc.read()
cv.imwrite(savepath+"/"+str(a)+".jpg",fream)
4、计算txt每行有多少字符(不包含标点符号)
import re
# 文件路径
file_path = ''
# 正则表达式,匹配中文字符,排除中文标点符号
chinese_char_pattern = re.compile(r'[\u4e00-\u9fa5]+')
# 正则表达式,匹配中文标点符号
chinese_punctuation_pattern = re.compile(r'[\u3000-\u303F|\uFF00-\uFFEF]+')
# 读取文件并计算每行的字数
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
# 移除中文标点符号
line_without_punctuation = chinese_punctuation_pattern.sub('', line)
# 使用正则表达式找到所有的中文字符
chinese_chars = chinese_char_pattern.findall(line_without_punctuation)
# 将找到的中文字符串连接起来,计算总字数
total_chars = sum(len(char) for char in chinese_chars)
print(f'第 {line.strip()} 行共有 {total_chars} 个字。')
C++:
1、记录某段区域 运行所花费的时间
auto start = std::chrono::system_clock::now(); //开始记录时间
/*
本区域为所要检测花费时间的 程序(代码)
*/
auto end = std::chrono::system_clock::now(); //推理结束时间
std::cout << "获取竖线位置 详细信息 耗时" <<
std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;
2、将视频每一帧保存为图片
#include <iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
Mat fream; //读取视频的视频帧(每一帧)
VideoCapture capture("2.mp4"); //读取图片路径
string path = "img/";//图片保存路径
int i = 0;
while (1)
{
capture >> fream; //获取视频的每一帧
if (fream.empty()) { //判断是否读取完视频
break;//读取完退出
}
//imshow("a", fream); //显示每一帧
//waitKey(100);
ostringstream oss; //用于记录图像的保存路径
oss << path << i++ << ".jpg"; //图像的保存路径
imwrite(oss.str(), fream);//保存图像
}
}
3、生成相机标定标定板(黑白格)
//编程环境:ubuntu16.04, qt,OpenCV3.1.16
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/calib3d/calib3d.hpp>
using namespace std;
using namespace cv;
int main() {
//单位转换
int dot_per_inch = 96; //我的电脑是96DPI(dot per inch)
double cm_to_inch = 0.3937; //1cm=0.3937inch
double inch_to_cm = 2.54; //1inch = 2.54cm
double inch_per_dot = 1.0 / 96.0;
//自定义标定板
double blockSize_cm = 2; //方格尺寸:边长2cm的正方形
//设置横列方框数目
int blockcol = 8;
int blockrow = 10;
int blockSize = (int)(blockSize_cm / inch_to_cm * dot_per_inch);
cout << "blockSize:" << blockSize << endl;
int imageSize = blockSize * blockSize;
int imagesizecol = blockSize * blockrow;
int imagesizerow = blockSize * blockcol;
cout <<"imageSize:" << imageSize << endl;
Mat chessBoard(imagesizecol, imagesizerow, CV_8UC3, Scalar::all(0));
unsigned char color = 0;
for (int i = 0; i < imagesizerow; i = i + blockSize) {
color = ~color;
for (int j = 0; j < imagesizecol; j = j + blockSize) {
Mat ROI = chessBoard(Rect(i, j, blockSize, blockSize));
ROI.setTo(Scalar::all(color));
color = ~color;
}
}
imshow("Chess board", chessBoard);
cout << "cols" << chessBoard.cols << endl;
cout << "rows" << chessBoard.rows << endl;
imwrite("H:/C++/camera_calibration/chessBoard3.jpg", chessBoard);
waitKey(0);
return 0;
}