机器学习常用小代码块

这个是我常用的代码,保存下来,以供以后使用方便。有些代码可能是直接从其他地方copy过来的,但是在文中不进行标注引用。特此声明。

github 仓库持续更新

Fly-Pluche/Code_block (github.com)

觉得好用的同学请给个Star

数据

NUMPY与TENSOR的转化

tensor -> numpy

np.array(data.cpu())或np.array(data.cpu().detch())

numpy-> tensor

torch.from_numpy(data)

tensor用size

numpy用shape

数据类型转化

得到数据类型

data.dtype()

数据类型转化

numpy:

mask=mask.astype(np.uint8)

一般是为了保存为图片,所以是8位

将在CUDA上的TORCH数据保存为图片

 import cv2
 mask3=src_bg_mask.squeeze(0).squeeze(0)
 mask3=np.array(mask3.cpu())     #转化到cpu,并转化为numpy
 mask3=mask3.astype(np.uint8)*255 # 将dtype 转化为uint8,自己看要不要×255 
 # cv2.imshow('mask3',mask3)
 #cv2.waitkey(0)
 cv2.imwrite('mask3.png',mask3)
 ​
 如果要保存的图片是三维的,就要在tensor的时候转化为(H,W,3)
         src_img=src_img.permute(1,2,0)

显卡

os.environ["CUDA_VISIBLE_DEVICES"] = "0"

文件读取

读取一个文件下的所有JPG图片

 import glob
 img_path_list=sorted(glob.glob(path+'/*.jpg'))
 # 其中的 jpg 可以改成其他类型

获取一个路径的前一个路径

 path='./outputs/results/demos/imitators/mixamo_preds/pred_00000100.jpg'
 b=path.split('/')
 path2='/'.join(i for i in b[:-1])
 # path2=''./outputs/results/demos/imitators/mixamo_preds'

得到原字符串右对齐,使用字符填充的固定长度字符串

 a=1
 a.rjust(4,'0')
 a='0001'

文件转化

将AVI MP4转化为GIF

  1. 首先 pip install moviepy

  2.  import moviepy.editor as mpy
     ​
     # 视频文件的本地路径
     def mp4_to_gif(path):
         content = mpy.VideoFileClip("D:/photo_video/qq/1.avi")
         #(avi->mp4)
         # 剪辑0分0秒到0分4秒的片段。resize为修改清晰度
         c1 = content.subclip()
         # c1 = content.subclip((0, 0), (0, 4)).resize((480, 320))
         # 将片段保存为gif图到python的默认路径
         c1.write_gif("D:/photo_video/qq/gav24.gif")

    我自己试过avi以及MP4都可以,其他的类型没有试过,你们可以自己have a try.

    将AVI GIF转为JPG,PNG

     import cv2
     from PIL import Image
     ​
     video_path = 'D:/photo_video/qq/0.gif'  # 视频或gif图像的路径
     save_path = 'D:/photo_video/qq/'  # 保存帧的路径
     a=video_path.split('/')
     name=a[-1][-3:]
     ​
     # 当打开一个序列文件时,PIL库自动加载第一帧。
     # 可以使用seek()函数和tell()函数在不同帧之间移动。实现保存
     if name == "avi":
         cap = cv2.VideoCapture(video_path)
         fps = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
         fps_count = 0
         for i in range(fps):
             ret, frame = cap.read()
             if ret:
                 cv2.imwrite(save_path + str(10000 + fps_count) + '.jpg', frame)
                 #(jpg->png)
                 fps_count += 1
     if name == "gif":
         im = Image.open(video_path)
         # 当打开一个序列文件时,PIL库自动加载第一帧。
         # 可以使用seek()函数和tell()函数在不同帧之间移动。实现保存
         try:
             while True:
                 current = im.tell()
                 # 为了保存为jpg格式,需要转化。否则可以保存为png
                 img = im.convert('RGB')
                 img.save(save_path + '/' + str(10000 + current) + '.jpg')
                             #(jpg->png)
                 im.seek(current + 1)
         except EOFError:
             pass

PYTHON将.PNG图片改为.JPG格式

 import os
 import re
 ​
 path="F:/xxx"
 file_walk = os.walk(path)
 fileNum = 0
 filesPathList = []
 for root, dirs, files in file_walk:
     # print(root, end=',')
     # print(dirs, end=',')
     # print(files)
     for file in files:
         fileNum = fileNum + 1
         filePath = root + '/' + file
         # print(filePath)
         filesPathList.append(filePath)
         protion = os.path.splitext(filePath)
         # print(protion[0],protion[1])
 ​
         if protion[1].lower() == '.png':
             print("正在处理:" + filePath)
             newFilePath = protion[0] + '.JPG'
             os.rename(filePath, newFilePath)

多张图片合成为GIF

  1. pip install imageio

 import imageio
 import os
 ​
 def create_gif(img_dir, image_list, gif_name, duration=0.05):
     frames = []
     for image_name in image_list:
         print("image_name={0} img_dir={1}".format(image_name, img_dir))
         frames.append(imageio.imread(img_dir + '/'+ image_name))
     imageio.mimsave(gif_name, frames, 'GIF', duration=duration)
     return
 ​
 def main():
     img_dir = './image_dir'
     duration = 0.05 # 每秒20帧
     image_list = os.listdir(img_dir + '/')
     gif_name = img_dir+'.gif'
     create_gif(img_dir, image_list, gif_name, duration)
 ​
 if __name__ == '__main__':
     main()

腐蚀,画框并裁剪

Net是一个抠图的网络,得到一个二值化的mask蒙版(只有黑白)

 mask = Net("0000.jpg")
 mask = mask.astype(np.uint8) * 255
     # mask=0,255
 print(mask.shape)
 img = mask.copy()
 mask = mask[:, :, 0]
     # mask两个维度
 cnts = (cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE))[0]
 ​
 c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]  # contourArea这计算图像轮廓的面积  从大到小排,取最大
 ​
 rect = cv2.boundingRect(c)  # minAreaRect就是求出在上述点集下的最小面积矩形
 ​
 x = rect[0]-10
 y = rect[1]-10
 wight = rect[2]
 height = rect[3]
 if height >= wight:
     x = x - (height - wight) / 2
     if x<0:
         x=0
     wight = height
 ​
 else:
     y = y - (wight-height) / 2
     if y<0:
         y=0
     height = wight
 ​
 box = [[x, y], [x + height, y], [x + wight, y + height], [x, y + height]]
 box = np.int64(box)
 ​
 a=cv2.imread('0000.jpg')
 final = cv2.drawContours(a, [box], -1, (0, 255, 0), 3)
 cv2.imshow("Image", final)
 ​
 print(a.shape)
 c=a[int(y):int(y+height),int(x):int(x+wight),:]
 print(c.shape)
 cv2.imshow("final",c)
 cv2.waitKey(0)
 # final=cv2.resize(255,255)
 ​
 print('---------------Finish-------------------')

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值