import cv2
import os
img=cv2.imread("文件路径")
img_shape=img.shape #返回(高,宽,通道)
img=cv2.resize(img,img_scale) # img_scale=(输出尺寸的宽,高)
img_crop=img[y0:y1,x0:x1] #裁剪
img=cv2.undistort(img_path, mtx, dist, None, undistort_mtx)#去畸变
img=cv2.imwrite("img_savepath", img)
basename=os.path.basename(img_path)#取后缀名
new_path=os.path.join('old_dir','.jpg')#将路径和后缀结合
#避免解码错误
img = cv2.imdecode(np.fromfile(in_imgfile,dtype=np.uint8),-1)
cv2.imencode('.jpg',img)[1].tofile(out_imgfile)
批量读取文件夹中的图片,并按照图片名数值从小到大排序读取。
import os
imgList=os.listdir(input_path)
imgList.sort()
for filename in imgList:
filepath=os.path.join(input_path,filename)#单张图片完整相对路径
从图片合成视频
将文件夹中图片排序读取,并合成视频
import os
import cv2
video_dst='./save.avi'#要生成的视频
imput_path='./input_images/'#被合成视频的图片文件夹所在路径
fps=10#帧率
img_size=(1290*2,1069)
fourcc=cv2.VideoWriter_fourcc('M','J','P','G')
videoWiter=cv2.VideoWriter(video_dst,fourcc,fps,img_size)
imgList=os.listdir(input_path)
imgList.sort()
for filename in imgList:
im_name=os.path.join(input_path,os.path.splitext(filename)[0]+'.png')
frame=cv2.imread(im_name)
videoWriter.write(frame)
print(im_name)
videoWriter.release()
python import os
使用汇总
input_path='/home/lcy/model/123.456.png'
input_path1='/home/lcy/model'
input_path2='123.456.png'
os.getcwd() #当前终端所在绝对路径
os.path.join() #会生成上面的input_path
os.path.splitext(input_path)[0] #去掉后缀名的图片名123.456
os.path.split(input_path)[0] #去掉包含后缀名的图片名视为路径/home/lcy/model/
input_path.split('.')[0] #123
os.path.dirname(input_path) #取文件夹路径
os.path.exists(os.path.dirname(input_path)) #看文件夹路径是否存在
if not os.path.exists(os.path.dirname(input_path)):
os.mkdir(os.path.dirname(input_path))
os.makedirs()
import pathlib
pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True)
#读取文件夹中文件
filelist = os.listdir(dir)
filelist.sort()
#读取txt文件
f = open(dir, 'r')
filelist = f.readlines
#直接加载txt内容
np.loadtxt(dir, dtype=np.float64).reshape(-1,5)
#写入文件
with open(dir, 'w') as f:
f.wite(lines)
注意:x和y均为int类型
python 画点
cv2.circle(img,(x,y),1,(0,255,255),4) #图 圆心 半径 颜色 圆边界线的粗细
python 画线
cv2.line(img,(x1,y1),(x2,y2),(0,0,255),8)
画框
cv2.rectangle(img, (bbox.left, bbox.top), (bbox.right, bbox.bottom), (0,0,255), 2)
左上角与右下角的x,y
python 批量画线
import cv2
import PIL.Image
import PIL.ImageDraw
img=cv2.imread('./img.jpg')
img_pil=PIL.Image.fromarray(img)
for i,lane in enumerate(lanes):
PIL.ImageDraw(img_pil).line(xy=lane,fill=(0,0,255),width=8)
#其中lane=(x,y),tuple类型
img_vis=np.array(img_pil,dtype=np.unit8)
cv2.imwrite('./result.jpg',img_vis)
log文件
在这里插入代码片
PIL转cv2
import cv2
from PIL import Image
import numpy
path = 'F:/File_Python/Resources/face_images/LZT01.jpg'
img = Image.open(path).convert("RGB")#.convert("RGB")可不要,默认打开就是RGB
img = cv2.cvtColor(np.array(img),cv2.COLOR_RGB2BGR)
cv2.imshow("OpenCV",img)
cv2.waitKey()
复制文件
import shutil
shutil.copy(input_img_path, save_img_path)