简体   繁体   English

如何使用Python正确读取PPM文件

[英]how to properly read a PPM file using Python

Here is my overall instructions 这是我的总体说明

Write a Color class that represents an RGB color using integer values in the range 0 to 255. Your class must: Be placed in image.py Provide a constructor that accepts the values of the red, green, and blue channels from the client and stores those values Provide public methods that return the values of the red, green, and blue channels 编写一个Color类,该类使用介于0到255之间的整数值表示RGB颜色。您的类必须:被放置在image.py中,提供一个构造函数,该构造函数接受来自客户端并存储的红色,绿色和蓝色通道的值这些值提供返回红色,绿色和蓝色通道值的公共方法

Write a PortablePixmap class that represents a PPM image. 编写一个表示PPM图像的PortablePixmap类。 Your class must: Be placed in image.py Provide a constructor that accepts the magic number, width, height, maximum color value, and pixel data from the client and stores those values Store the pixel data as a list of (or list of lists of) Color objects Provide a public method that returns a string representation of the PPM image 您的课程必须:被放置在image.py中。提供一个构造器,该构造器从客户端接受幻数,宽度,高度,最大颜色值和像素数据,并将这些值存储起来。将像素数据存储为(或列表列表)的颜色对象提供一个公共方法,该方法返回PPM图像的字符串表示形式

Write a read_ppm function that opens a PPM image file, reads its contents, and returns a PortablePixmap object that holds its contents. 编写read_ppm函数,以打开PPM图像文件,读取其内容并返回保存其内容的PortablePixmap对象。 Your function must: Be placed in image.py Read the contents of a PPM image file Not be sensitive to the formatting of the PPM image file Exit with an error if the numbers of expected and provided pixels differ 您的函数必须:放置在image.py中。读取PPM图像文件的内容对PPM图像文件的格式不敏感。如果预期像素数和提供的像素数不同,则返回错误

Write a main function that tests your read_ppm function. 编写一个主函数来测试您的read_ppm函数。 Your function must be placed in main.py 您的函数必须放在main.py中

this is what I have thus far 这就是我到目前为止

class Color:
# constructor takes in values from client and stores them
def __init__(self, red, green, blue): 


    # checks that type of arg == int: raises exception otherwise 
    if (isinstance(red, int) and isinstance(green, int) and isinstance(blue, int)):     
        print("good stuff, indeed integers")
    else:   
        raise TypeError("Argument must be an integer.")

    # checks if values are between 0 and 225 
    if red < 0 or red > 225: 
        print("0 < rgb values < 225")
    elif green < 0 or green > 225:
        print("0 < rgb values < 225") 
    elif blue < 0 or blue > 225:
        print("0 < rgb values < 225")

    # instance variables (RGB values)
    self._red = red 
    self._green = green
    self._blue = blue 


# methods that reuturn RGB values
def returnRed(self): 
    return self._red 

def returnGreen(self):
    return self._green

def returnBlue(self):
    return self._blue


'''class that represents a PPM image'''
class PortablePixmap:
    def __init__(self, magic_number, width, height, max_color_value, pixel_data):
        self._magic_number = magic_number
        self._width = width
        self._height = height
        self._max_color_value = max_color_value
        self._pixel_data = pixel_data


    def __str__(self):
        s = self._magic_number
        s += '\n' + str(self._width)
        s += ' ' + str(self._height)
        s += '\n' + str(self._max_color_value)
        for pixel in self._pixel_data:
            s += ' ' + str(pixel[0])
            s += ' ' + str(pixel[1])
            s += ' ' + str(pixel[2])

        return s

I have a few questions for clarification.. 1. Did I go about creating the Color class correctly? 我有几个问题需要澄清。1.我是否正确创建了Color类? 2. Do I even need to raise any exceptions in that class specifically? 2.我什至需要在该课程中专门提出任何例外情况吗? We will ultimately be reading from a file that contains everything in order but not necessarily on it's own individual line. 最终,我们将从一个按顺序包含所有内容的文件中进行读取,但不一定是在其单独的一行上。

I really just want to know if I am going about this correctly. 我真的只想知道我是否正确进行此操作。 The instructions seem stepwise, but I am not really understanding how everything connects so I'm afraid I am either doing too much or too little. 这些说明似乎是逐步的,但我并不是很了解所有事物之间的联系,因此我担心自己做得太多或太少。

Thanks in advance 提前致谢

It is not clear from the specification that you need to check the values, and your checks only raise exceptions in some cases, otherwise cause side effects (printing); 从规范中不清楚您是否需要检查这些值,并且检查仅在某些情况下会引发异常,否则会导致副作用(打印); from a reuse perspective, I'd prefer to have only the exceptions if any. 从重用的角度来看,我宁愿只包含例外(如果有)。 Aside from the indentation error (which I assume is only here, not in your source) the Color class looks to cover the demands, although they are quite unpythonic with the accessors; 除了缩进错误(我认为只是在这里,而不是在您的源代码中)之外,Color类看起来可以满足需求,尽管它们与访问器完全无关。 probably someone was trained by Java. 可能有人受过Java培训。

The docstring should be inside the PortablePixmap class, not above it. 该文档字符串应位于PortablePixmap类内部,而不是其上方。

Most remarkable is the combination of demands that your class not be sensitive to the formatting of the PPM and store pixels as 8-bit unsigned RGB. 最引人注目的是要求您的类不给PPM 存储像素作为8位无符号RGB的格式敏感的组合。 This makes it impossible to support all PPMs, as they support 16-bit values (note the maxval field in the PPM format ). 这使得不可能支持所有PPM,因为它们支持16位值(请注意PPM格式的maxval字段)。

Your PortablePixmap class also doesn't use the Color class: "Store the pixel data as a list of (or list of lists of) Color objects". 您的PortablePixmap类也不使用Color类:“将像素数据存储为Color对象的列表(或Color对象的列表)”。 That requirement forces a rather awfully inefficient implementation, but the whole thing is an exercise, I suppose. 该要求迫使实施起来效率非常低下,但是我想这整个过程都是一种练习。 You'll need to extract the RGB triplets from the pixel data string. 您需要从像素数据字符串中提取RGB三胞胎。 That's also where you need the one check that is specified; 这也是您需要指定的一张支票的地方; verifying that there are exactly the right number of pixels. 验证像素数是否正确。 One would expect a ValueError exception if that fails. 如果失败,可能会遇到ValueError异常。

If I were writing this sort of thing I might have used slots to reduce memory use for classes like Color, arrays to handle the large number of limited range numeric values, and possibly properties to make storage transparent without using unwieldy getter methods. 如果我正在写这种东西,我可能会使用插槽来减少诸如Color之类的内存使用,使用数组来处理大量有限范围的数值,并可能使用一些属性来使存储透明而不使用笨拙的getter方法。 split and join would make it easier to handle the collection of pixels. 拆分合并将使处理像素集合更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM