Skip to content

Instantly share code, notes, and snippets.

@jdmichaud
Created July 24, 2018 20:04
Show Gist options
  • Save jdmichaud/21645a184966c48da7a624845335c99b to your computer and use it in GitHub Desktop.
Save jdmichaud/21645a184966c48da7a624845335c99b to your computer and use it in GitHub Desktop.
Subsample artefact
import math
import numpy
import imageio
from matplotlib import pyplot
def resize(img, size):
(width, height) = size
resized = []
wratio = len(img[0]) / width
hratio = len(img) / height
for i in range(height):
resized.append([])
for j in range(width):
resized[i].append(img[math.floor(i * hratio)][math.floor(j * wratio)])
return resized
def subsample(img, startX, startY, step):
width = len(img[0])
height = len(img)
resized = []
for i in range(math.floor(height / step)):
resized.append([])
for j in range(math.floor(width / step)):
resized[i].append(img[math.floor(i * step + startX)][math.floor(j * step + startY)])
return resized
def merge(img, subsample, startX, startY, step):
width = len(img[0])
height = len(img)
for i in range(math.floor(height / step)):
for j in range(math.floor(width / step)):
img[i * step + startX][j * step + startY] = subsample[i][j]
return img
# img = [
# [1, 0, 0, 1],
# [0, 0, 0, 0],
# [0, 0, 0, 0],
# [1, 0, 0, 1],
# ]
im = imageio.imread('lena.png')
original_width = len(im[0])
original_height = len(im)
print(f'{original_width}x{original_height}')
# Convert to grayscale
img = [[math.floor(0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) for p in row] for row in im]
subsampled0 = subsample(img, 0, 0, 2)
imageio.imwrite('subsampled0.png', numpy.asarray(subsampled0))
reconstructed = resize(subsampled0, (original_width, original_height))
imageio.imwrite('subsampled0_resized.png', numpy.asarray(reconstructed))
reconstructed = merge(reconstructed, subsample(img, 1, 1, 2), 1, 1, 2)
imageio.imwrite('merged_with_subsample1.png', numpy.asarray(reconstructed))
reconstructed = merge(reconstructed, subsample(img, 1, 0, 2), 1, 0, 2)
imageio.imwrite('merged_with_subsample2.png', numpy.asarray(reconstructed))
reconstructed = merge(reconstructed, subsample(img, 1, 0, 2), 1, 0, 2)
imageio.imwrite('merged_with_subsample3.png', numpy.asarray(reconstructed))
# [print(row) for row in subsampled0]
# pyplot.imshow(reconstructed, cmap='gray')
# pyplot.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment