10

I have an image F of size 1044*1408, it only has 3 integer values 0, 2, and 3.

I want to shrink it to 360*480. Now I am using Z= cv2.resize(F,(480,380)). But Z is interpolated, it has many unique values, more than just 0, 2 and 3. I can't just round up the interpolated values to the closest integer, because I will get some 1s.

F is read from a tif file and manipulated, it is an ndarray now. So I can't use PIL: F = F.resize((new_width, new_height)) as F is not from F = Image.open(*).

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
Echo
  • 667
  • 3
  • 8
  • 19
  • 2
    What you want is probably resampling the image instead of resizing it. Since you mention `ndarray`, I assume you are using `numpy`. Look at the solution ("numpy slicing") in http://stackoverflow.com/questions/25876640/subsampling-every-nth-entry-in-a-numpy-array It will allow resampling (subsampling) without interpolation. – Sci Prog Sep 16 '16 at 02:46
  • shouldn't CV_INTER_NN "interpolation" method choose one of the original pixel values (the one with the smallest distance to the resized pixel position)? – Micka Sep 16 '16 at 08:54
  • Yes set `interpolation=cv2.INTER_NEAREST` will let you use the nearest pixel value. I can use `Z= cv2.resize(F,(480,380),interpolation=cv2.INTER_NEAREST)`, to get only 0,2 and 3. I am wondering is there any method that doesn't do interpolation at all – Echo Sep 16 '16 at 15:44

2 Answers2

16

You may use INTER_NEAREST:

Z= cv2.resize(F,(480,380),fx=0, fy=0, interpolation = cv2.INTER_NEAREST)
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160
11

Alternately, you can also use skimage.transform.resize. Argument order = 0 enforces nearest-neighbor interpolation.

   Z = skimage.transform.resize(F,
                               (480,380),
                               mode='edge',
                               anti_aliasing=False,
                               anti_aliasing_sigma=None,
                               preserve_range=True,
                               order=0)
Daniel R. Livingston
  • 1,227
  • 14
  • 36