Conversion between Pillow Image object and numpy array changes dimension

后端 未结 3 1333
离开以前
离开以前 2020-12-25 13:03

I am using Pillow and numpy, but have a problem with conversion between Pillow Image object and numpy array.

when I execute following code, the result is weird.

3条回答
  •  青春惊慌失措
    2020-12-25 13:35

    actually this is because most image libraries give you images that are transpozed compared to numpy arrays. this is (i think) because you write image files line by line, so the first index (let's say x) refers to the line number (so x is the vertical axis) and the second index (y) refers to the subsequent pixel in line (so y is the horizontal axis), which is against our everyday coordinates sense.

    If you want to handle it correctly you need to remember to write:

    image = library.LoadImage(path)
    array = (library.FromImageToNumpyArray(image)).T
    

    and consequently:

    image = library.FromNumpyArrayToImage(array.T)
    library.WriteImage(image, path)
    

    Which works also for 3D images. But i'm not promising this is the case for ALL image libraries - just these i worked with.

提交回复
热议问题