在windows上使用Python读写PGM文件

2024-06-25 23:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在pgm文件的末尾加上一个pgm文件的结果是一样的 我的问题是,这个脚本在Linux上运行得很好,但是当我在windows10上使用它时,输出的pgm是有缺陷的,只是一些白色的垂直线

请注意,我还不能上传图片

 #!/usr/bin/python
import sys
import os

# End of function

#################################################

def parseArgs( argv):
    expectedInputLen = 3
    if( len( argv) != expectedInputLen):
        print "Failure: bad number of input argument = %d (expectedInputLen=%d)\n" % (len(argv), expectedInputLen)
        print ("usage %s sensorID pgmFn \n")
        sys.exit(1)

    argI = 1
    sensorID = argv\[argI\]; argI = argI + 1
    pgmFn = argv\[argI\]; argI = argI + 1
    if( pgmFn\[-4:\] != '.pgm'):
        print("Failure: not a pgm file\n")
        sys.exit(1)

    print "input: "
    print "\t sensorID = <%s>" % sensorID
    print "\t pgmFn = <%s>" % pgmFn

    assert( argI == len( argv))

    return { 'sensorID':sensorID,
    'pgmFn':pgmFn}

# End of function

#################################################

def implantSID( pgmFileIn, pgmFileOut, sensorID):

    #read header and asserts
    implantedStr = "sensorID" + sensorID + "sensorID"
    assert( pgmFileIn.read(2) == 'P5')
    pgmFileIn.read(1)
    width = int(pgmFileIn.read(4))
    assert( width == 1280)
    pgmFileIn.read(1)
    height = pgmFileIn.read(3)
    if( height != '960'):
        height = height + pgmFileIn.read(1)
        assert( height == '1080')
    height = int(height)
    pgmFileIn.read(1)
    depth = int(pgmFileIn.read(5))
    assert depth <= 65535
    pgmFileIn.read(1)

    pgmFileOut.write('P5 ' + str(width) + ' ' + str(height) + ' ' + str(depth) + '\n')
    for row in range(height-1):
        for col in range(width):
            pgmFileOut.write(pgmFileIn.read(2))

    for col in range(width-len(implantedStr)):
        pgmFileOut.write(pgmFileIn.read(2))

    for char in implantedStr:
        pgmFileOut.write('\0'+char)

    # End of function

#################################################

def main( argv):
    '''Main entry point, start the application's main loop.'''

    params = parseArgs( argv)
    sensorID = params\['sensorID'\]
    pgmFn = params\['pgmFn'\]

    pgmFileIn = open( pgmFn, 'r')
    pgmFileOut = open( pgmFn.replace(".pgm", "_SID.pgm"), 'w')

    implantSID( pgmFileIn, pgmFileOut, [enter image description here][1]sensorID)
    pgmFileIn.close()
    pgmFileOut.close()

# End of function

#################################################

if __name__ == "__main__":

    main( sys.argv)

# End of function

#################################################

Tags: ofreadfunctionassertwidthendprintheight