https://colab.research.google.com/github/
然后把ipynb文件的github地址复制过去
import os
from google.colab import files
def traverse_dir(data_dir):
file_name_list = os.listdir(data_dir)
for file_name in file_name_list:
files.download('{}/{}'.format(data_dir, file_name)) # 多层文件夹需要修改这里
traverse_dir('/content/PhotoWCT2/figures/style') # 文件路径
from google.colab import drive, output
import os
import json
%cd /content/
!rm -rf '/content/wct2'
!git clone https://github.com/chiutaiyin/PhotoWCT2.git # 代码仓地址
%cd /content/PhotoWCT2 # 修改当前工作路径
from tkinter import filedialog
filepath = filedialog.askopenfilename() # 选择文件,路径保存于filepath中
使用Python中的os模块下的方法listdir()是一个不错的选择,样例如下:
import os
os.listdir()
上面的代码将打印当前路径下所有文件和目录的名称。
如果我们想基于特定路径来打印结果,只需传递给函数os.listdir() 相应的参数,举例如下:
os.listdir(myPath)
如果想知道当前运行脚本的目录:
currentdir = os.path.dirname(__file__)
parentdir = os.path.abspath(os.path.join(currentdir, os.pardir))
os.path的用法
def renaming(file):
"""修改后缀"""
ext = os.path.splitext(file) # 将文件名路径与后缀名分开
if ext[1] == '.jpg': # 文件名:ext[0]
new_name = ext[0] + '.bmp' # 文件后缀:ext[1]
os.rename(file, new_name) # tree()已切换工作地址,直接替换后缀
elif ext[1] == '.jpeg':
new_name = ext[0] + '.bmp'
os.rename(file, new_name)
path = r'C:\Users\Desktop\wallpaper' # 文件目录
for filename in os.listdir(path):
oripath = path + os.sep + filename # 获取绝对路径
os.chdir(path) # 修改工作地址(相当于文件指针到指定文件目录地址)
renaming(oripath) # 修改后缀
def tree(path):
"""递归函数"""
files = os.listdir(path) # 获取当前目录的所有文件及文件夹
for file in files:
file_path = os.path.join(path, file) # 获取该文件的绝对路径
if os.path.isdir(file_path): # 判断是否为文件夹
tree(file_path) # 开始递归
else:
os.chdir(path) # 修改工作地址(相当于文件指针到指定文件目录地址)
renaming(file) # 修改后缀
def mycopyfile(srcfile, dstpath): # 复制文件
if not os.path.isfile(srcfile):
print("%s not exist!" % (srcfile))
else:
fpath, fname = os.path.split(srcfile) # 分离文件名和路径
if not os.path.exists(dstpath):
os.makedirs(dstpath) # 创建路径
shutil.copy(srcfile, dstpath + os.sep + fname) # 复制文件
print("copy %s -> %s" % (srcfile, dstpath + fname))
path1 = r'C:\Users\Desktop\wallpaper\0a2efbd136628de3094007cf3c8f3cdd.bmp'
path2 = r'C:\Users\Desktop\wallpaperedit'
mycopyfile(path1, path2)
def del_file(path_data):
for i in os.listdir(path_data) :# os.listdir(path_data)#返回一个列表,里面是当前目录下面的所有东西的相对路径
file_data = path_data + os.sep + i#当前文件夹的下面的所有东西的绝对路径
if os.path.isfile(file_data) == True:#os.path.isfile判断是否为文件,如果是文件,就删除.如果是文件夹.递归给del_file.
os.remove(file_data)
else:
del_file(file_data)
from PIL import Image
img1 = Image.open(bp).convert("RGBA")
# img转换为cv用的arry
CVarray= np.array(PILimg)
import cv2
img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGR)
# cv用的arry转换为img
PIVimg = Image.fromarray(CVarray)
PIVimg .save("out.jpeg")
from PIL import Image
img=Image.open('d:/dog.png')
img.show()
import cv2
img_grayscale = cv2.imread('test.jpg',0)
cv2.imshow('graycsale image',img_grayscale)
cv2.waitKey(0)
path = r'C:\Users\Desktop\wallpaper'
sourcepath = r'D:\algorithm\Color-Transfer-between-Images-master\Color-Transfer-between-Images-master\source'
resultpath = r'D:\algorithm\Color-Transfer-between-Images-master\Color-Transfer-between-Images-master\result'
savepath = r'C:\Users\Desktop\wallpaperedit'
# mycopyfile(path1, path2)
# del_file(sourcepath)
for filename in os.listdir(path):
oripath = path + os.sep + filename
mycopyfile(oripath, sourcepath)
color_transfer()
del_file(sourcepath)
oriimg = Image.open(oripath)
sp = oriimg.size
joint = Image.new("RGBA", (sp[0]*10, sp[1]))
joint.paste(oriimg, (0, 0))
idx = 1
for imgname in os.listdir(resultpath):
curimgpath = resultpath + os.sep + imgname
curimg = Image.open(curimgpath)
loc = (sp[0]*idx, 0)
joint.paste(curimg, loc)
idx += 1
pth = savepath + os.sep + filename
joint.save(pth)
del_file(resultpath)
base 64 :
import base64
data1 = base64.b64encode(open('C:/Users/l00817249/Desktop/universe.bmp', 'rb').read())
data2 = data1.decode('utf-8')
print(data2)
im = base64.b64decode(data2)
img = cv2.imdecode(np.frombuffer(im, dtype=np.uint8), -1)
cv2.imshow('graycsale image', img)
cv2.waitKey(0)
python 生成 exe
import os
import cv2
def extract_mask(mskpath, oripath, savepath, oriformat):
"""
用于根据分割掩膜从视频提取分割物体
从分割得到的RGBmask图片获取mask的A通道图像
mskpath和oripath的文件需要有相同的图片名称
:param mskpath: 原始的分割掩膜路径
:param oripath: 原始图片的路径
:param savepath: 提取出分割物体的存储路径
:param oriformat: 生成图的格式,.jpg/.png
:return: 保存结果到savepath
"""
for filename in os.listdir(mskpath):
# 读取文件夹中的每个文件
maskpath = mskpath + os.sep + filename # 获取掩膜绝对路径
realfilename = filename.split('.')
# 读取原始素材的路径
originalpath = oripath + os.sep + realfilename[0] + oriformat
# 读取图片
mskimg = cv2.imread(maskpath, cv2.IMREAD_UNCHANGED) # 掩模图
msktmp = cv2.cvtColor(mskimg, cv2.COLOR_BGR2GRAY)
# 掩模图转化为二值图
thresh, mask = cv2.threshold(msktmp, 0, 255, cv2.THRESH_BINARY)
# 原图
oriimg = cv2.imread(originalpath, cv2.IMREAD_UNCHANGED)
# 提取图片
im = cv2.bitwise_and(oriimg, oriimg, mask=mask)
finalsavepath = savepath + os.sep + filename
cv2.imwrite(finalsavepath, im, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
import os
import cv2
def build_video(refvideopath, resourcepath, imgfmt, savepath, savename):
"""
从一系列的图片生成视频
:param refvideopath:原视频的路径,用来根据原始视频的帧率设定处理之后视频的帧率
:param resourcepath:图片序列的路径
:param imgfmt:图片格式,.png/.jpg
:param savepath:保存的路径
:param savename:保存的名字
:return:保存视频
"""
videoCapture = cv2.VideoCapture(refvideopath) # 读取视频文件
fps = videoCapture.get(cv2.CAP_PROP_FPS) # 计算视频的帧率
# 图片文件夹路径和格式(例如:/path/to/folder/*.jpg)
img_folder = resourcepath
img_format = imgfmt
# 视频文件保存路径和名称
video_name = savename
# 获取图片列表
img_list = sorted([os.path.join(img_folder, f) for f in os.listdir(img_folder) if f.endswith('.' + img_format)])
# 读取第一张图片,获取图片尺寸
img = cv2.imread(img_list[0])
height, width, channels = img.shape
# 创建视频编写器
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 定义视频编码器
savepath = savepath + os.sep + video_name
video = cv2.VideoWriter(savepath, fourcc, fps, (width, height)) # 定义视频文件,帧率为读取到的fps
# 逐个将图片写入视频文件
for img_path in img_list:
img = cv2.imread(img_path)
video.write(img)
# 释放资源
video.release()
from PIL import Image
import numpy as np
def combinevideo(mskpath, oripath, segpath, oriformat, savepath):
"""
将分割得到的前景和背景组合展示
:param mskpath: 掩膜的路径,即png中A通道的路径
:param oripath: 背景图的路径
:param segpath: 前景图的路径
:param oriformat: 背景图图像格式
:param savepath: 保存路径
:return: 保存粘贴好的图片
"""
for filename in os.listdir(mskpath):
maskpath = mskpath + os.sep + filename # 获取掩膜绝对路径
realfilename = filename.split('.')
originalpath = oripath + os.sep + realfilename[0] + oriformat
segmentationpath = segpath + os.sep + filename
mskimg = cv2.imread(maskpath, cv2.IMREAD_UNCHANGED) # 掩模图
oriimg = cv2.imread(originalpath, cv2.IMREAD_UNCHANGED) # 原图
segimg = cv2.imread(segmentationpath, cv2.IMREAD_UNCHANGED) # 分割图
height, width, channels = segimg.shape
oriimg = cv2.resize(oriimg, (width, height), interpolation=cv2.INTER_AREA)
msktmp = cv2.cvtColor(mskimg, cv2.COLOR_BGR2GRAY)
thresh, msk = cv2.threshold(msktmp, 0, 255, cv2.THRESH_BINARY)
# im = cv2.bitwise_and(oriimg, segimg)
oriimg = cv2.cvtColor(oriimg, cv2.COLOR_BGR2RGB)
segimg = cv2.cvtColor(segimg, cv2.COLOR_BGR2RGB)
ORIimg = Image.fromarray(oriimg)
SEGimg = Image.fromarray(segimg)
MSKimg = Image.fromarray(msk)
# MSKimg.show()
ORIimg.paste(SEGimg, (0, 0), mask=MSKimg)
# ORIimg.show()
finalsavepath = savepath + os.sep + filename
CVarray = np.array(ORIimg)
CVarray = cv2.cvtColor(CVarray, cv2.COLOR_RGB2BGR)
cv2.imwrite(finalsavepath, CVarray, [int(cv2.IMWRITE_JPEG_QUALITY), 100])