如何使用图像模块在Python中扩展图像?

时间:2014-02-25 05:13:21

标签: python image python-2.7 scale

无法附加图像,但它没有填充新的4像素块。它交替并在2个通道中留下黑色像素。

def scale_up(img):
"""
(Image object) -> Image object
Returns a copy of img that is blown up by a factor of 2.  The new 
image is twice as wide and twice as high.  Each pixel in the original 
image is mapped to the corresponding 4 pixels in new image.
"""
w = img.width()
h = img.height()
scale_up_img = image.new_image(w * 2, h * 2)

# loop over every (x,y) pair
for x in range(w):
    for y in range(h):
        # get rgb values
        r, g, b = img.get_rgb(x, y)
        scale_up_img.set_rgb(x * 2 + 1, y * 2 + 1, r, g, b)
        scale_up_img.set_rgb(x * 2, y * 2, r, g, b)
return scale_up_img  # return img object

http://i.stack.imgur.com/8yVMK.jpg

1 个答案:

答案 0 :(得分:0)

由于每个输出像素由4个输入像素副本组成,因此需要4个语句来设置它们。

    scale_up_img.set_rgb(x * 2 + 1, y * 2 + 1, r, g, b)
    scale_up_img.set_rgb(x * 2 + 1, y * 2, r, g, b)
    scale_up_img.set_rgb(x * 2, y * 2 + 1, r, g, b)
    scale_up_img.set_rgb(x * 2, y * 2, r, g, b)