Skip to content

获取图片非透明部分的纵坐标

代码

python
from PIL import Image

def get_extremity_h(im):
    def gen_hw(im):
        for y in range(im.height):
            for x in range(im.width):
                yield (x, y)
    hs = []
    im_data = im.getdata()
    for index, hw in enumerate(gen_hw(im)):
        if im_data[index] != (0, 0, 0, 0):
            hs.append(hw[1])
    return min(hs), max(hs)

def main():
    im = Image.open('part.png')
    min_h, max_h = get_extremity_h(im)
    print(min_h, max_h)

if __name__ == '__main__':
    main()

Released under the MIT License.