3、python 视频帧转图片及裁剪

背景:从视频中获取图片,进行数据标注,然后进行训练;

指定文件夹读取视频然后产生相应图片工具

# -*- coding: utf-8 -*-
import os
import cv2
import os.path
source_path=r'/home/ubuntu/video/'
destion_path=r'/home/ubuntu/image/'
rule=r'.mp4'
def get_files(path, rule):
	all = []
	for fpathe,dirs,fs in os.walk(path):
		for f in fs:
			filename = os.path.join(fpathe,f)
			if filename.endswith(rule): 
				all.append(filename)
	return all
b = get_files(source_path,rule)
for path_video in b:
	vc = cv2.VideoCapture(path_video)
	print (path_video)
	(filepath, tempfilename) = os.path.split(path_video)
	(filename, extension) = os.path.splitext(tempfilename)
	print (filename)
	c=0
	rval=vc.isOpened()
	while rval:
		c = c + 1
		rval, frame = vc.read()
		if rval:
			cv2.imwrite(destion_path+filename+str(c) + '.jpg', frame)
			img = cv2.imread(destion_path+filename+str(c) + '.jpg')			
			rows,cols,chanel = img.shape
			M = cv2.getRotationMatrix2D(((cols-1)/2.0,(rows-1)/2.0),180,1)
			dst = cv2.warpAffine(img,M,(cols,rows))
			cv2.imwrite(destion_path+filename+str(c) + '.jpg', dst)
			print(c)
		else:
			break
	vc.release()

图片进行180°翻转;

from PIL import Image
import os
import os.path
 
rootdir = r'picture'
for parent, dirnames, filenames in os.walk(rootdir):
    for filename in filenames:
        print('parent is :' + parent)
        print('filename is :' + filename)
        currentPath = os.path.join(parent, filename)
        print('the fulll name of the file is :' + currentPath)
 
        im = Image.open(currentPath)
        out = im.transpose(Image.ROTATE_180)
        newname=filename
        out.save(rootdir+'/'+newname)

图片进行某区域裁剪;

from PIL import Image
import os
fin = 'picture'
fout = 'picture'
for file in os.listdir(fin):
    file_fullname = fin + '/' +file
    (filepath, tempfilename) = os.path.split(file_fullname)
    (filename, extension) = os.path.splitext(tempfilename)
    if extension=='.jpg':
       img = Image.open(file_fullname)
       a = [179, 296,  1119, 704]
       box = (a)
       roi = img.crop(box)
       out_path = fout + '/' + file
       roi.save(out_path)

 

你可能感兴趣的:(Python基础知识)