一个处理图片的python脚本:移除所有的非jpg文件

在机器学习中免不了和图片打交道。有时候收集来的图片后缀名和实际类型会存在不一致的情况,这里可能就需要涉及到图片文件的批量处理。简单粗暴上代码:

import struct 
import os
def gci(filepath):
  files = os.listdir(filepath)
  for fi in files:
    fi_d = os.path.join(filepath,fi)            
    if os.path.isdir(fi_d):
      gci(fi_d)                  
    else:
      tempP = os.path.join(filepath,fi_d)
      tp = filetype(tempP)
      if tp != 'JPEG':
        print(tempP)
        os.remove(tempP)
        #print tempP

def typeList():  
  return {  
    "FFD8FF": "JPEG",  
    "89504E47": "PNG",
    "47494638": "GIF"}  
    

def bytes2hex(bytes):  
  num = len(bytes)  
  hexstr = u""  
  for i in range(num):  
    t = u"%x" % bytes[i]  
    if len(t) % 2:  
      hexstr += u"0"
    hexstr += t  
  return hexstr.upper()  

def filetype(filename):  
  binfile = open(filename, 'rb') 
  tl = typeList()  
  ftype = 'unknown'
  for hcode in tl.keys():  
    numOfBytes = len(hcode) / 2 
    binfile.seek(0) 
    hbytes = struct.unpack_from("B"*numOfBytes, binfile.read(numOfBytes))
    f_hcode = bytes2hex(hbytes)  
    if f_hcode == hcode:  
      ftype = tl[hcode]  
      break
  binfile.close()  
  return ftype  



gci('your_img_folder_path')
复制代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值