File Processing by Python

2023-11-16

Go through all the file in destination path:

import os
import sys

def GetFileList(dir, fileList):
    newDir = dir
    if os.path.isfile(dir):
        fileList.append(dir.decode('gbk'))
    elif os.path.isdir(dir):  
        for s in os.listdir(dir):
            newDir=os.path.join(dir,s)
            GetFileList(newDir, fileList)  
    return fileList
def MyGetFileList(dir, filelist):
    if os.path.isdir(dir):
        for s in os.listdir(dir):
            if re.match(r"([\s\S]*)\.yuv", s):
                filelist.append(os.path.join(dir, s))
    return filelist 

ValueError: invalid literal for int() with base 10
When read file, we just want to calculate the ASCII value to achieve our goal. Here MAP is very important.

def CalculatePSNRForTwoYUVs(f1, f2, dir1, dir2):                
        d1 = dir1 + '\\' + f1
        d2 = dir2 + '\\' + f2
        if (os.path.isfile(d1) and os.path.isfile(d2)):
            file1Object = open(d1, 'r')
            file2Object = open(d2, 'r')
            while True:
                chunk1 = file1Object.read(1)
                chunk2 = file2Object.read(1)
                if chunk1 == '':
                    break
                #print string.atoi(chunk1)  
                ck1 = map(ord, chunk1)
                print ck1[0]
def CalculatePSNRForTwoYUVs(f1, f2, dir1, dir2):                
        d1 = dir1 + '\\' + f1
        d2 = dir2 + '\\' + f2
        sumOfPSNR = 0
        if (os.path.isfile(d1) and os.path.isfile(d2)):
            file1Object = open(d1, 'r')
            file2Object = open(d2, 'r')
            print d1
            print d2
            while True:
                chunk1 = file1Object.read(1)
                chunk2 = file2Object.read(1)
                if chunk1 == '':
                    break
                if chunk2 == '':
                    break
                ck1 = map(ord, chunk1)
                ck2 = map(ord, chunk2)  
                while ck1[0] >= 255 or ck1[0] < 0:
                    chunk1 = file1Object.read(1)
                    ck1 = map(ord, chunk1)
                while ck2[0] >= 255 or ck2[0] < 0:
                    chunk2 = file2Object.read(1)    
                    ck2 = map(ord, chunk2)
                if ck1[0] != ck2[0]:            
                    print ck1[0],"  ",ck2[0]
                sumOfPSNR += abs(ck1[0] - ck2[0])
        print sumOfPSNR
        print "---------------------------------------------------------\n"     

If we just want to change ‘1’ to int, just string.atoi or string.atol
totalCount = ‘234’
totalPage = int(totalCount)/35

How to calculate PSNR:
Peak Signal to Noise Ratio
这里写图片描述
这里写图片描述
这里写图片描述
其中,MSE是原图像与处理图像之间均方误差。  
MAXI:表示图像颜色的最大数值,8位采样点表示为255。
Peak就是指8bits表示法的最大值255。MSE指MeanSquareError,I(角标n)指原始影像第n个pixel值,P(角标n)指经处理后的影像第n个pixel值。PSNR的单位为dB。所以PSNR值越大,就代表失真越少。
Here I give an example for a batch to calculate PSNR of a lot YUV file.

If U need calculate YUV whole plane:
tmpy = (float)(4.0 / pow(10, snr_y / 10));

tmpu = (float)(1.0 / pow(10, snr_u / 10));

tmpv = (float)(1.0 / pow(10, snr_v / 10));

snr_yuv = (float)(10 * log10(6 / ( tmpy + tmpu + tmpv ) ));

#-*-coding:utf-8-*-

'''
Create on 2015/11/16 9:05:59
@author: Chen Yu in RockChip Internship 
'''

import os
import sys
import re
import string
import math

# processing folder path
dirGood = r"E:\ErrorConcealment\Sequence\Sequence_Bat_Good"
dirCopy = r"E:\ErrorConcealment\Sequence\Sequence_Bat"
dirFirstBatch = r"E:\ErrorConcealment\Sequence\Sequence_Bat\First Batch"
dirSecondBatch = r"E:\ErrorConcealment\Sequence\Sequence_Bat\Second Batch"  

def MyGetFileList(dir, filelist):
    if os.path.isdir(dir):
        for s in os.listdir(dir):
            if re.match(r"([\s\S]*)\.yuv", s):
                filelist.append(s)
    return filelist             

def CalculatePSNRForTwoFolder(fileList1, fileList2, dir1, dir2):
    for f1 in fileList1:
        for f2 in fileList2:
            if f1 == f2:
                CalculatePSNRForTwoYUVs(f1, f2, dir1, dir2)

def CalculatePSNRForTwoYUVs(f1, f2, dir1, dir2):                
        d1 = dir1 + '\\' + f1
        d2 = dir2 + '\\' + f2
        sumOfPSNR = 0
        if (os.path.isfile(d1) and os.path.isfile(d2)):
            file1Object = open(d1, 'rb')
            file2Object = open(d2, 'rb')
            print d1
            print d2
            while True:
                chunk1 = file1Object.read(1)
                chunk2 = file2Object.read(1)
                '''
                if not chunk1:  
                    break
                if not chunk2:  
                    break     
                '''
                if chunk1 == '':
                    print ck1
                    break
                if chunk2 == '':
                    print ck2
                    break   
                ck1 = ord(chunk1)
                ck2 = ord(chunk2)   
            #   if ck1 != ck2:          
            #       print ck1,"  ",ck2, "  ", sumOfPSNR
                sumOfPSNR += (abs(ck1 - ck2)**2)
        file1Object.close()
        file2Object.close() 
        print sumOfPSNR
        MSE = math.sqrt(sumOfPSNR)
        print MSE
        if MSE != 0:
            MAXDivMSE = 255 / MSE
        if MAXDivMSE > 0:
            PSNR = 20 * log10(MAXDivMSE)
        print PSNR  
        print "---------------------------------------------------------\n\n"       

def BatchCalculatePSNR():
    FileListOfGood = MyGetFileList(dirGood, [])
    FileListOfCopy = MyGetFileList(dirCopy, [])
    FileListOfFirstBatch = MyGetFileList(dirFirstBatch, [])
    FileListOfSecondBatch = MyGetFileList(dirSecondBatch, [])

    CalculatePSNRForTwoFolder(FileListOfGood, FileListOfCopy, dirGood, dirCopy)
#   CalculatePSNRForTwoFolder(FileListOfGood, FileListOfFirstBatch, dirGood, dirFirstBatch) 
#   CalculatePSNRForTwoFolder(FileListOfGood, FileListOfSecondBatch, dirGood, dirSecondBatch)   

if __name__ == "__main__":
    BatchCalculatePSNR()    

Some blog I think is helpful to understand file operation:

http://maincoolbo.iteye.com/blog/626655
http://blog.csdn.net/nanjunxiao/article/details/9086079
http://www.sharejs.com/codes/python/4611
http://www.cnblogs.com/ylan2009/articles/2382868.html
http://www.jb51.net/article/47956.htm
http://www.mamicode.com/info-detail-308445.html

Type Tranformation

http://www.xuebuyuan.com/1884369.html
http://www.cnblogs.com/allenblogs/archive/2010/09/13/1824842.html

Some Mistakes
Maybe U find that using read(1) is too slow and U can read all the file one time.

if __name__ == "__main__":
    d1 = "E:/ErrorConcealment/Sequence/Sequence_Bat/Basketball_1920x1080_frame2_confirm.264.yuv"
    d2 = "E:/ErrorConcealment/Sequence/Sequence_Bat_Good/Basketball_1920x1080_frame2_confirm.264.yuv"
    result = re.findall("([\s\S]*)\_(\d+)x(\d+)\_([\s\S]*)",d1)
    for line in result:
        width = string.atoi(line[1])
        height = string.atoi(line[2])
    Area = width * height   
    chunkSize = (Area * 3) >> 1  # 420
    frameNum = 0
    MSE = 0
    MAXDivMSE = 0
    PSNR = 0
    if (os.path.isfile(d1) and os.path.isfile(d2)):
        file1Object = open(d1, 'rb')
        file2Object = open(d2, 'rb')
        while True:
            chunk1 = file1Object.read(chunkSize)
            chunk2 = file2Object.read(chunkSize)
            if not chunk1:  
                break
            if not chunk2:  
                break     
            sumOfPSNR = 0   
            l1 = list(chunk1)
            l1 = list(chunk2)
            for i in range (0, Area):       
                ck1 = ord(l1[i])
                ck2 = ord(l2[i])    
                sumOfMSE += (abs(ck1 - ck2)**2)
            MSE = math.sqrt(sumOfPSNR)
            if MSE != 0:
                MAXDivMSE = 255 / MSE   
            if MAXDivMSE > 0:
                PSNR = 20 * math.log10(MAXDivMSE)       
            frameNum++          
        file1Object.close()
        file2Object.close() 
        print PSNR  
        print "---------------------------------------------------------\n\n"       
    #win32api.ShellExecute(0, 'open', 'F:/My_Tool/evalvid-2.7-w32/psnr.exe', '1920 1080 420 Basketball_1920x1080_frame2_confirm.264.yuv Basketball_1920x1080_frame2_confirm_copy.yuv > F:/My_Tool/evalvid-2.7-w32/ref_psnr.txt',"", 0)      
    # BatchCalculatePSNR()  
    # os.system('F:/My_Tool/evalvid-2.7-w32/psnr.exe 1920 1080 420 F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm.264.yuv F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm_copy.yuv > F:/My_Tool/evalvid-2.7-w32/ref_psnr.txt')
    # win32api.ShellExecute(0, 'open', 'F:/My_Tool/evalvid-2.7-w32/psnr.exe','1920 1080 420 F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm.264.yuv F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm_copy.yuv >F:/My_Tool/evalvid-2.7-w32/ref_psnr2.txt','',1) 
    '''
    cmda = 'F:/My_Tool/evalvid-2.7-w32/psnr.exe 1920 1080 420 F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm.264.yuv F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm_copy.yuv > F:/My_Tool/evalvid-2.7-w32/ref_psnr1.txt'
    p = Popen(cmda, shell = True, stdout = PIPE, stderr = PIPE)
    output = p.communicate()[0] #标准输出
    error = p.communicate()[1] #标准错误
    #p.terminnate() #杀死进程   
    cmda = 'F:/My_Tool/evalvid-2.7-w32/psnr.exe 1920 1080 420 F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm.264.yuv F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm_copy.yuv > F:/My_Tool/evalvid-2.7-w32/ref_psnr2.txt'
    p2 = Popen(cmda, shell = True, stdout = PIPE, stderr = PIPE)
    ''' 
    '''
    handle = win32process.CreateProcess('F:/My_Tool/evalvid-2.7-w32/psnr.exe','1920 1080 420 F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm.264.yuv F:/My_Tool/evalvid-2.7-w32/Basketball_1920x1080_frame2_confirm_copy.yuv > F:/My_Tool/evalvid-2.7-w32/ref_psnr2.txt', None , None , 0 ,win32process. CREATE_NO_WINDOW , None , None , win32process.STARTUPINFO())
    win32event.WaitForSingleObject(handle[0], -1) #win32process.TerminateProcess(handle[0],0)
    '''
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

File Processing by Python 的相关文章

  • C++ Template Class List

    转载请注明 http blog csdn net c602273091 article details 50717999 Introduction STL STL Standard Template Library 标准模板库 是惠普实验室
  • 写论文注意事项

    文献检索 搜索引擎的高级功能 搜索引擎主要www google com和scholar google com www baidu com则仅在检索中文时稍好点 英文很差 用处不大 我们常用的google侧重于网页的检索 Scholar则主要
  • Some Laws in IT

    Moore s Law 摩尔定律是由英特尔 Intel 创始人之一戈登 摩尔 Gordon Moore 提出来的 其内容为 当价格不变时 集成电路上可容纳的元器件的数目 约每隔18 24个月便会增加一倍 性能也将提升一倍 换言之 每一美元所
  • Jitter Removal in Image and Sequence

    去除重影 消抖 在 jitter removal images and video sequences Using robust decision Based Adaptive spatio temporal median Algorith
  • Conference and Journal Level in 2016

    中国计算机学会推荐国际学术会议和期刊目录 2015 年 中国计算机学会 中国计算机学会推荐国际学术期刊 计算机体系结构 并行与分布计算 存储系统 一 A 类 序号 刊物简称 刊物全称 出版社 网址 1 TOCS ACM Transactio
  • Video Evaluation by Python

    Here is the code to calculate for PSNR and SSIM of YUV My code has its advantage that it can process the problem by batc
  • Latex Skills

    ModernCV http 519488126 blog 163 com blog static 722401602014010555221 Paper 1 Blank 两个quad空格 a qquad b a qquad b 两个m的宽度
  • Evaluate Video Quality

    How to evaluate video PSNR and SSIM PSNR is easy to calculate http blog csdn net c602273091 article details 49861817 SSI
  • ML Introduction

    Task of ML Supervised Learning Classification and regression Unsepervised Learning Clustering Density Estimation Reducti
  • Visual Assist X AND MSDN

    assist X 推荐 这款插件是visual studio或者vc的插件 没想到vs用起来也可以这么爽 用起来居然比sourceinsight还好用 好用到哭 好用到哭 好用到哭 自动补全 补全的时候还可以看到对这个补全的东西的介绍 鼠标
  • SourceInght And Sublime Text 2 Using Skills

    工欲善其事 必先利其器 Sourceinsight 加入时间 http my oschina net xDreamYY blog 228814 Sourceinsight 加入快捷键 http www cnblogs com wangqig
  • 有实力的人才能谈梦想

    我总是徘徊 在犹豫 觉得自己做不到 只是在苟延残喘摆了 所谓的目标也不可能实现 今天我发现我做到了 原来也不是那么遥不可及 是自己不够自信 不够淡定 有实力的人聊梦想 没理想的人就想想怎么混工作吧 有实力的人 自信 坚定的毅力 不怕失败 淡
  • memset in C++ and C

    definition memset是计算机中C C 语言函数 将s所指向的某一块内存中的前n个 字节的内容全部设置为ch指定的ASCII值 第一个值为指定的内存地址 块的大小由第三个参数指定 这个函数通常为新申请的内存做初始化工作 其返回值
  • IMAGE REGISTRATION

    Classification Nature area based and feature based Different viewpoints multiview analysis image from different viewpoin
  • Latex Picture And Table Setting

    Four Picture in one column begin figure htb begin minipage b 48 linewidth centering centerline includegraphics width 4 0
  • Python之PyAudio使用

    PyAudio 播放 录音 回放 回调方法播放 非阻塞回调 PyAudio 使用这个可以进行录音 播放 生成wav文件等等 播放 coding utf 8 引入库 import pyaudio import wave import sys
  • File Processing by Python

    Go through all the file in destination path import os import sys def GetFileList dir fileList newDir dir if os path isfi
  • ML Impossible and Rescure

    No Rule to Define will cause conflict Using available data to estimate target function if without rule target is unknown
  • Binary Classification Core PLA

    Target Step Verify My verification Pocket Algorithm Pros Cons of PLA
  • Process in Shell

    PID current process Get Process Get Process Select Object Name Get Process processname jm Select Object Get Process proc

随机推荐

  • 计算机的计算单位

    容量单位 在物理层面 高低电平记录信息 理论上只认识0 1两种状态 0 1能够表示的内容太少了 需要更大的容量表示方法 0 1称为bit 比特位 字节 1Byte 8bits 硬盘商一般使用10进位标记容量 500G一般格式化后只剩465G
  • Postgresql ODBC驱动,用sqlserver添加dblink跨库访问postgresql数据库

    在同样是SQLserver数据库跨库访问时 只需要以下方法 declare rowcount int set rowcount 0 set rowcount select COUNT from sys servers where name
  • APP自动化测试-7.移动端web app自动化测试

    APP自动化测试 7 移动端纯web应用测试 文章目录 APP自动化测试 7 移动端纯web应用测试 前言 一 移动端应用分类简述 二 web app基础配置 1 基础信息获取 2 驱动配置 3 启动 三 元素定位 总结 前言 移动端应用细
  • 在虚拟机上ifconfig结果中eth0没有IP地址(inet4)而是显示的是inet6

    问题描述 在虚拟机上执行ifconfig 结果中eth0没有显示IP地址inet4 而是显示inet6 出现原因 虚拟机上没有连接网络 解决方法 启动网卡 执行命令 ifup eth0 衍生问题 当执行上述命令时 却报如下错误 some o
  • 小程序工作学习:值的传递与操作以及target,options区别

    最近做小程序相关的东 学艺不精原理不了解 在前端界面的问题上遇到很多问题 好在在别人的帮助下以及在查资料补漏过程中还是有点收获的 问题 一 关于请求中如何能把这个页面的一下参数传递给下一页面 不能总是重复调用接口访问后台 这样的话影响加载页
  • python中jupyter notebook安装教程、常用插件和拓展配置及基本使用(全面)

    文章目录 1 jupyter安装 2 jupyter常用插件配置 2 1 Jupyter Notebook和conda的环境和包管理工具nb conda 2 2 Jupyter Notebook扩展jupyter contrib nbext
  • c#基础知识---集合之排序列表(SortedList)

    SortedList 类代表了一系列按照键来排序的键 值对 这些键值对可以通过键和索引来访问 排序列表是数组和哈希表的组合 它包含一个可使用键或索引访问各项的列表 如果您使用索引访问各项 则它是一个动态数组 ArrayList 如果您使用键
  • 【Spring】AOP实例—日志模块的实现

    AOP实例 日志模块 AOP能够使系统服务 例如 日志模块 安全模块 事务管理 模块化 并以声明的方式将它们应用到它们需要影响的组件中去 使业务组件会具有更高的内聚性并且会更加关注自身的业务 完全不需要了解涉及系统服务所带来复杂性 日志模块
  • Java BufferImage图片处理(获取宽高、图片截取、转换灰度图)

    Java BufferImage图片处理 获取宽高 截取 转换灰度图 1 效果图 2 源码 参考 这篇博客将介绍如何使用Java读取图片为byte 数组 或者BufferedImage及互相转换 并进行了转换图片为灰度图 截取部分区域等 1
  • 电脑win+r命令大全

    0 osk 打开键盘 1 msconfig 关闭系统开机启动项 2 ipconfig all ipconfig release ipconfig renew 3 convert g fs ntfs 盘符格式转换 g代表U盘符 4 gpedi
  • DSS部署-完整版

    文章目录 DSS部署流程 第一部分 背景 第二部分 准备虚拟机 环境初始化 1 准备虚拟机 2 环境初始化 关闭防火墙 关闭selinux 关闭swap 根据规划设置主机名 在master添加hosts 将桥接的IPv4流量传递到iptab
  • 现在机器人是用什么语言编程

    现在机器人是用什么语言编程 对于很多的家长们来说 孩子的学习一直都是他们非常关心和重视的一件事情 很多的家长在培养孩子的学习方面也可以说是相当的认真的 他们会给孩子选择一些能够有利于孩子成长的课程 就拿现在很多的家长想要孩子去学习机器人编程
  • 【搜索引擎Solr】Apache Solr 神经搜索

    Sease 1 与 Alessandro Benedetti Apache Lucene Solr PMC 成员和提交者 和 Elia Porciani Sease 研发软件工程师 共同为开源社区贡献了 Apache Solr 中神经搜索的
  • 【开发】前端工程——ReactJS

    前置知识 JavaScript ES6 ReactJS 前端开发的四个阶段 1 静态页面阶段 在第一个阶段中前端页面都是静态的 所有前端代码和前端数据都是后端生成的 前端纯粹只是增加一些特殊效果 后端MVC模式 Model 模型层 提供 保
  • 删除重复字符排序字符串(python3)

    问题描述 编写一个程序 从键盘接收一个字符串 然后按照字符顺序从小到大进行排序 并删除重复的字符 输入形式 从键盘输入一个字符串 以回车结束输入 要求程序可以处理含有空格的字符串 输出形式 程序接收此字符串 然后将其按照字符ASCII码值从
  • vue阶段思维导图

  • springboot 打印请求路径到 日志 控制台

    文章目录 application properties 添加 logging level org springframework web servlet mvc method annotation RequestMappingHandler
  • 安装双系统后,将windows设置为默认启动选项的方法

    原先的电脑只有windows系统 后来加装了ubuntu系统 但由于大部分时间仍然需要使用windows 但是默认启动项为ubuntu 难免会带来一些不便 将windows设为默认第一启动项的方法很简单 打开终端 查看grub的配置文件 s
  • VC++实用宏定义

    前言 在日常的编程工作中 常常定义一些实用的宏方便调用 该文章将收集一些常用的宏供大家参考 欢迎大家讨论和添加 指针释放 最常用的就是指针的安全释放 对应new的释放 ifndef ReleasePtr define ReleasePtr
  • File Processing by Python

    Go through all the file in destination path import os import sys def GetFileList dir fileList newDir dir if os path isfi