python3 处理seq文件

最近接手一批seq的图片文件,处理方式也是有的。[引]

但是是该代码只能在python2下运行,我一脚踩到python3这个坑里面来了,最后还是找到了为什么不能在python3下运行的原因,如下

 strings 分别在 Python2、Python 3下[]

What is tensorflow.compat.as_str()?

Python 2 将 strings 处理为原生的 bytes 类型,而不是 unicode, 

Python 3 所有的 strings 均是 unicode 类型。

再后来就找到了填坑方式:

#第一处
  string = str(f.read())
#改为==>
  string = f.read().decode('latin-1')

#第二处
             i.write(splitstring)
             i.write(img)
#改为==>
             i.write(splitstring.encode('latin-1'))
             i.write(img.encode('latin-1'))

下面还有啥print的格式常规修改,文件路径修改,酌情处理,大功告成!!

--------------------------------------------------------------------------------------------------

我也将我修改过的源码分享出来,在python3.6下运行没有问题。

--------------------------------------------------------------------------------------------------

# Deal with .seq format for video sequence
# Author: Kaij
# The .seq file is combined with images,
# so I split the file into several images with the image prefix
# "\xFF\xD8\xFF\xE0\x00\x10\x4A\x46\x49\x46".

import os.path
import fnmatch
import shutil

def open_save(file,savepath):
    # read .seq file, and save the images into the savepath

    f = open(file,'rb+')
    string = f.read().decode('latin-1')
    # PNG
    # splitstring = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"
    splitstring = "\xFF\xD8\xFF\xE0\x00\x10\x4A\x46\x49\x46"
    # split .seq file into segment with the image prefix
    strlist=string.split(splitstring)
    f.close()
    count = 0
    # delete the image folder path if it exists
    if os.path.exists(savepath):
        shutil.rmtree(savepath)
    # create the image folder path
    if not os.path.exists(savepath):
        os.mkdir(savepath)
    # deal with file segment, every segment is an image except the first one
    for img in strlist:
        filename = str(count)+'.jpg'
        filenamewithpath=os.path.join(savepath, filename)
        # abandon the first one, which is filled with .seq header
        if count > 0:
            i=open(filenamewithpath,'wb+')
            i.write(splitstring.encode('latin-1'))
            i.write(img.encode('latin-1'))
            i.close()
        count += 1

if __name__=="__main__":
    rootdir = "./set_data/set01"
    # walk in the rootdir, take down the .seq filename and filepath
    for parent, dirnames, filenames in os.walk(rootdir):
        for filename in filenames:
            # check .seq file with suffix
            if fnmatch.fnmatch(filename,'*.seq'):
                # take down the filename with path of .seq file
                thefilename = os.path.join(parent, filename)
                # create the image folder by combining .seq file path with .seq filename
                thesavepath = parent+'/'+filename.split('.')[0]
                print ("Filename=" + thefilename)
                print ("Savepath=" + thesavepath)
                open_save(thefilename,thesavepath)

你可能感兴趣的:(python,tensorflow,python,人工智能)