5

I have an image and I want to resize and expand this image without spoiling it.

The image:

Image work

The image size:

  • w=41
  • h=43

The image size I want it resized to:

  • w=2000x
  • h=2100

I tried all the known methods:

  1. with PIL.Image:
    from PIL import Image
    path = "image.png"
    w, h = 2000, 2100
    img = Image.open(path)
    img = img.resize((w, h), Image.ANTIALIAS)
    img.save("re_image.png", "PNG")
    
  2. with cv2:
    import cv2
    path = "image.png"
    w, h = 2000, 2100
    img = cv2.imread(path)
    img = cv2.resize(img, (w, h), interpolation = cv2.INTER_AREA)
    cv2.imwrite("re_image.png", img)
    

The result is:

Result Image

1
  • It depends on what you want the final image to look like. If you want it to keep it's pixelation the cv2.INTER_NEAREST is probably your best bet. All methods of interpolating between existing pixels will create some artefact. Especially at the scales you are attempting. Commented Jan 15, 2020 at 12:39

3 Answers 3

6

Don't use the ANTIALIAS filter. Since you want to preserve the sharpness of the edges, simply use the NEAREST filter. This filter is the default if no argument is passed to the resample parameter of Image.resize

img = img.resize((w, h))

This gives the expected result

Expected Result

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

Comments

1

For your specific case which is a binary image, I think that you want to keep the edges sharp. Then I would suggest to use the flag cv2.INTER_NEAREST in your openCV implementation. You can check the effect of the different interpolation types, given in the documentation: https://docs.opencv.org/4.1.1/da/d54/group__imgproc__transform.html

I hope this helps!

1 Comment

If you use Pillow, it looks like NEAREST is not default so you have you use img = img.resize((w, h), PIL.Image.NEAREST)
-1

I created a simple function. Please give me your opinion.

The function is:

 import cv2, numpy as np

 def resize(path, sizes = (500, 800)):
         nw, nh = sizes
         g_img = cv2.imread(path)

         gw, gh = g_img.shape[0], g_img.shape[1]
         nw, nh = gw+510, gh+510
         pw, ph = int(nw/gw), int(nh/gh)
         if (pw == 0):pw = 1
         if (ph == 0):ph = 1
         nw, nh = pw*gw, ph*gh

         cvimg = np.zeros((nh,nw,3), np.uint8)

         for gy in range(gh):
             y, h = gy*ph, (gy*ph)+ph
             for gx in range(gw):
                 x, w = gx*pw, (gx*pw)+pw
                 cvimg[y:h, x:w] = g_img[gy:gy+1, gx:gx+1]

         nsize = [nw, nh]
         return cvimg, nsize

The result is:

Result

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.