Error Converting PIL B&W images to Numpy Arrays

后端 未结 2 851
离开以前
离开以前 2020-12-11 21:25

I am getting weird errors when I try to convert a black and white PIL image to a numpy array. An example of the code I am working with is below.

    if image         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 21:56

    Not sure about this line:

    data = numpy.array(image)
    

    In fact, that gives me a segfault. But I just tried the following, and it works fine:

    import numpy
    import Image
    
    im = Image.open("some_photo.jpg")
    im = im.convert("1")
    
    pixels = im.getdata() # returns 1D list of pixels
    n = len(pixels)
    data = numpy.reshape(pixels, im.size) # turn into 2D numpy array
    
    for row in data:
        # do your processing
        pass
    
    # Check that the numpy array's data is good
    im2 = Image.new("1", im.size)
    im2.putdata(numpy.reshape(data, [n, 1]))
    im2.show()
    

提交回复
热议问题