缩小图像尺寸

时间:2018-06-24 22:21:24

标签: python numpy opencv image-processing python-imaging-library

我在这方面真的很困惑。图像中的每个正方形均包含许多像素,其中一些正方形较大,例如,一个正方形的宽度可能为9且高度为8,而另一个正方形的宽度可能为7且高度为8。我想做的是从此初始图像中创建一个较小的图像,其中每个正方形代表一个像素,所有像素的大小相同。

enter image description here

我已经为灰度图像做到了,但是不幸的是,我得到了错误的结果,即结果图像不是输入图像的精确副本

输入图片

enter image description here

输出图像

enter image description here

灰度图像代码

from PIL import Image
import numpy as np

name1 = raw_input("What is the name of the .png file you want to open? ")

filename1 = "%s.png" % name1

img = Image.open(filename1).convert('L')  # convert image to 8-bit grayscale
WIDTH, HEIGHT = img.size

a = list(img.getdata()) # convert image data to a list of integers
# convert that to 2D list (list of lists of integers)
a = np.array ([a[offset:offset+WIDTH] for offset in range(0, WIDTH*HEIGHT, WIDTH)])

print " "
print "Intial array from image:"  #print as array
print " "
print a

rows_mask = np.insert(np.diff(a[:, 0]).astype(np.bool), 0, True)
columns_mask = np.insert(np.diff(a[0]).astype(np.bool), 0, True)
b = a[np.ix_(rows_mask, columns_mask)]

print " "
print "Subarray from Image:"  #print as array
print " "
print b

print " "
print "Subarray from Image (clearer format):"  #print as array
print " "
for row in b: #print as a table like format
    print(' '.join('{:3}'.format(value) for value in row))

img = Image.fromarray(b, mode='L')

img.save("chocolate.png")


#print np.mean(b) #finding mean

0 个答案:

没有答案