0

I have an image, read into np.array by PIL. In my case, it's a(1000, 1500) np.array.

I'd like to simplify it for visualisation purposes. By simplification, I following transformation from this matrix

1 1 1 1 0 0
1 0 1 0 0 0 

to

1 1 0

so, essentially, look at every 2*2 sample, if it satisfies some criteria, like more than 50% of 1's -> count it as a 1, if not, count is as a 0.

I don't know how to call it properly, but I believe there should be some well known mathematic procedure for doing so.

1
  • 1
    the mathematic procedure I think you're talking about is often referred to as "downsampling" Wikipedia has a little page with a visual comparison of several of the popular methods Commented Oct 6, 2016 at 14:31

2 Answers 2

1

Use a combination of np.reshape() and np.sum(array) with axis argument.:

import numpy as np
a = np.array([[1, 1, 1, 1, 0, 0], [1, 0, 1, 0, 0, 0]])
a = np.reshape(a, (a.shape[0]/2, 2, a.shape[1]/2, 2))
a = np.sum(a, axis=(1, 3)) >= 2

The reshaping groups your array into small 2x2 blocks (the orginals axis lengths must be multiples of 2), I then use sum along the created axis to check that at least of the 4 values in the group is 1.

See Computing average for numpy array for similar question.

Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't that be >2 instead?
1

You could use PIL.Image.fromarray to take the image into PIL, then resize or convert that image into a thumbnail of your desired size. one benefit is this can be easily saved to file, drawn to a canvas, or displayed for debugging. only be aware of numeric types and image modes (a pitfall I often fall into).

creating the image is done by:

from PIL import Image
image = Image.fromarray(arr).astype(np.uint8) #unsigned bytes for 8-bit grayscale
smallerImage = image.resize(desired_size, resample=Image.BILINEAR) #resize returns a copy thumbnail modifies in place

Getting the image back to a numpy array is as simple as: np.array(image.getdata()).reshape(image.size)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.