如果无指定文件夹则创建文件夹,有则打印文件夹已存在。
def mkdir(path):
folder = os.path.exists(path)
if not folder:
os.makedirs(path)
else:
print("There is this folder!")
roots = "C:\\Users\\ps\\Desktop\\jupyter\\images\\imgs\\"
names = os.listdir(roots)
names.sort(key=lambda x:int(x[:-4]))
print(names)
def fileNames(root, suffix=None):
names = os.listdir(root)
result = []
if suffix:
for name in names:
if os.path.splitext(name)[1] == suffix:
result.append(name)
else:
result = names
return result
import os
os.rename(old_path, new_path)
import cv2
import os
def ImageRead(image_name, image_path):
"""
image_name: 图像名如(50.BMP)
image_path: 图像所属路径
"""
image = cv2.imread(os.path.join(image_path, image_name))
if image is None:
print("%s read failed"%(image_name))
return image
image_try = ImageRead('50.BMP')
print(image_try.shape)
impot cv2
def Gray(image):
if image.shape[2] == 3:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
gray = image.copy()
return gray
gray_try = Gray(image_try)
print(gray_try.shape)
while(1):
cv2.imshow('image', img)
if cv2.waitKey(20) & 0xFF == 27:
break
cv2.destroyAllWindows()
import cv2
"""
鼠标左键按下返回此时坐标值并以此为矩形左上顶点
鼠标左键放开返回此时坐标值并以此为矩形右下顶点
鼠标移动时显示坐标点及对应图像灰度或RGB值
"""
def draw_rectangle(event, x, y, flags, param):
global ix, iy
if event == cv2.EVENT_LBUTTONDOWN:
ix, iy = x, y
print("left up point:=", x, y)
elif event == cv2.EVENT_LBUTTONUP:
print("right down point:=", x, y)
print("width=", x-ix)
print("height=", y-iy)
cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 2)
elif event == cv2.EVENT_MOUSEMOVE:
rint("点(%d,%d)图像灰度为:%s"%(x, y, img[y, x]))
img = cv2.imread("...\\138.BMP")
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_rectangle)
while(1):
cv2.imshow('image', img)
if cv2.waitKey(20) & 0xFF == 27:
break
cv2.destroyAllWindows()
def Threshold(image, high_threshold, low_threshold):
rows = image.shape[0]
columns = image.shape[1]
for row in range(rows):
for column in range(columns):
if image[row][column] < low_threshold or image[row][column] > high_threshold:
image[row][column] = 0
from __future__ import print_function
import importlib
# check that all package are install
required_packages = { ' ',
' ',
}
problem_packages = list()
# Iterate over the required packages: If the package is not installed
# Ignore the exception
for package in required_packages:
try:
p = importlib.inport_module(package)
except ImportError:
probles_package.append(package)
if len(problem_packages) is 0:
print('All is well.')
else:
print('The following packages are required but not installed: + ','.join(problem_packages))
with open(path, 'r') as txtFile:
for line in txtFile:
radian = math.pi
angle = math.degrees(radian)
angle = 27
radian = math.radians(angle)
from xml.dom.minidom import Document
import os
import cv2
dic = {'0':"g", '1':"b", '2':"gc", '3':"cu"}
def CreateElement(builder, element, content):
ele = builder.createElement(element)
cont = builder.createTextNode(content)
ele.appendChild(cont)
return ele
def Txt2Xml(txt_path, xml_path, img_path):
names = os.listdir(txt_path)
for i, name in enumerate(names):
xml_builder = Document()
annotation = xml_builder.createElement("annotation")
xml_builder.appendChild(annotation)
img = cv2.imread(img_path+name[0:-4]+".bmp")
num_height, num_width, num_depth = img.shape
flag = 0
with open(os.path.join(txt_path, name), 'r') as txt_file:
for txt_line in txt_file:
flag += 1
txt_line_str = txt_line.strip().split(" ")
folder = CreateElement(xml_builder, "folder","VOC2007" )
if 1 == flag:
filename = CreateElement(xml_builder,"filename",name[0:-4]+".jpg" )
annotation.appendChild(filename)
size = xml_builder.createElement("size")
width = CreateElement(xml_builder, "width", str(num_width))
size.appendChild(width)
height = CreateElement(xml_builder,"height",str(num_height))
size.appendChild(height)
depth = CreateElement(xml_builder,"depth", str(num_depth))
size.appendChild(depth)
annotation.appendChild(size)
obj = xml_builder.createElement("object")
img_name = CreateElement(xml_builder,"name", dic[txt_line_str[0]])
obj.appendChild(img_name)
pose = CreateElement(xml_builder,"pose","Unspecified")
obj.appendChild(pose)
truncated = CreateElement(xml_builder,"truncated","0")
obj.appendChild(truncated)
difficult = CreateElement(xml_builder,"difficult","0")
obj.appendChild(difficult)
bndbox = xml_builder.createElement("bndbox")
mathData=int(((float(txt_line_str[1]))*num_width+1)-(float(txt_line_str[3]))*0.5*num_width)
xmin = CreateElement(xml_builder,"xmin",str(mathData))
bndbox.appendChild(xmin)
mathData = int(((float(txt_line_str[2]))*num_height+1)-(float(txt_line_str[4]))*0.5*num_height)
ymin = CreateElement(xml_builder,"ymin", str(mathData))
bndbox.appendChild(ymin)
mathData = int(((float(txt_line_str[1]))*num_width+1)+(float(txt_line_str[3]))*0.5*num_width)
xmax = CreateElement(xml_builder,"xmax", str(mathData))
bndbox.appendChild(xmax)
mathData = int(((float(txt_line_str[2]))*num_height+1)+(float(txt_line_str[4]))*0.5*num_height)
ymax = CreateElement(xml_builder,"ymax", str(mathData))
bndbox.appendChild(ymax)
obj.appendChild(bndbox)
annotation.appendChild(obj)
with open(xml_path+name[0:-4]+".xml", 'w') as xml_file:
xml_builder.writexml(xml_file, indent='\t', newl='\n', addindent='\t', encoding='utf-8')
txt_path = ".\\txt\\"
xml_path = ".\\xml\\"
img_path = ".\\imgs\\"
Txt2Xml(txt_path, xml_path, img_path)
import math
class Point(object):
def __init__(self, xParam = 0.0, yParam = 0.0):
self.x = xParam
self.y = yParam
def __str__(self):
return "(%.3f, %.3f)"(self.x, self.y)
def distance(self, pt):
xDiff = self.x - pt.x
yDiff = self.y - pt.y
return math.sqrt(xDiff ** 2 + yDiff ** 2)
def sin(self, pt):
dist = self.distance(pt)
yDiff = abs(self.y - pt.y)
return yDiff/dist
def cos(self, pt):
dist = self.distance(pt)
xDiff = self.x - pt.x
return xDiff/dist
def tan(self, pt):
xDiff = self.x - pt.x
yDiff = self.y - pt.y
return yDiff/xDiff
def arctan(self, pt):
return np.degrees(np.arctan(self.tan(pt)))
def arcsin(self, pt):
return np.degrees(np.arcsin(self.sin(pt)))
def arccos(self, pt):
return np.degrees(np.arccos(self.cos(pt)))
def sun(self, pt):
xNew = self.x + pt.x
yNew = self.y + pt.y
return Point(xNew, yNew)
pip install PyInstaller
Pyinstaller -F -i name.ico name.py
python代码用的我另一篇博客python_文件夹操作
"""
时间: 2022/01/24
作者: qiangyunLi, 深圳市宇瞳创新科技有限公司
需求描述:
- 自动生成文件夹
- 名字为 **年_月_日_时_分_序列号**
- 序列号从1开始,升序排列。
"""
import os
import time
root = os.getcwd()
t = time.localtime()
path = str(t.tm_year)+"_"+str(t.tm_mon)+"_"+str(t.tm_mday)+"_"+str(t.tm_hour)+"_"+str(t.tm_min)
names = os.listdir(root)
i = 1
while(True):
create_pat = path + "_" + str(i)
folder = os.path.exists(create_pat)
if folder:
i = i+1
else:
os.makedirs(create_pat)
break
我把这个代码封装成了exe文件,具体封装过程可看上述创建exe文件
exe文件已上传
python -V
python3 中,可以用中文作为变量名,非ASCII标识码也是允许了。通常情况下不建议使用
我们不能将他们用作任何标识符名称。利用标准库提供的keyword模块,可以输出当前版本的所有关键字。
>>> import keyword
>>> keyword.kwlist
['False','None','True','and', 'as','assert','async','await', 'break','class', 'continue','def','del','elif',
'else', 'except', 'finally', 'for', 'from','global', 'if', 'import','in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass','raise', 'return', 'try', 'while', 'with','yield']
缩进的空格数是可变的,但是同一个代码快的语句必须包含相同的缩进空格数。
语句很长,可以使用反斜杠 \ ;在[]、{}、()中不需要使用反斜杠。
语句间用(;)分隔。
print默认输出是换行的,要不换行在变量末尾加上end=“”。
变量不需要声明,每个变量在使用前必须赋值,变量赋值后才会被创建。
变量没有类型,类型是指变量所指的内存中对象的类型。
允许同时为多个变量赋值
a = b = c = 1
isinstance 和 type
del: 可以删除一些对象的引用和单个或多个对象。
一个变量可以通过赋值指向不同类型的对象。(注意变量在多次地方可能发生改变)
/ 返回一个浮点数,// 返回一个整数;
将数据类型作为函数名即可。
键必须不可变;
迭代器对象从集合的第一个元素开始访问,直到所有元素被访问结束,只往前;
iter(), next()
yield
def functionname[args, var_args_tupe):
加了 * 号的参数会以元组的形式导入,存放所有未命名的参数变量;
加了 **的参数会以字典的形式导入;
使用单独号作为参数,*号后的参数必须使用关键字参数;
python 3.8 中 / 指明/前必须使用位置参数。
一个模块被另一个程序第一次引入时,其主程序将运行。如果我们想在模块被引入时,模块中的某一程序块不执行,我们可以用__name__属性来使该程序块仅在该模块自身运行时执行。
if name == ‘main’:
print(‘程序自身在运行’)
else:
print(‘我来自另一模块’)
内置的函数 dir() 可以找到模块内定义的所有名称。以一个字符串列表的形式返回:
Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如 if/elif/else/、try/except、for/while等)是不会引入新的作用域的,也就是说这些语句内定义的变量,外部也可以访问,
len() 返回的长度是从1开始算的。
[print(x) for x in (x ** 2 for x in range(5))]
// 两个in,一个生成list,一个生成迭代器
sum([ x ** 2 for x in range(10000000)])
sum(x ** 2 for x in range(10000000)])