opencv icon indicating copy to clipboard operation
opencv copied to clipboard

INTER_NEAREST_EXACT not giving expected result wrt PIL and scikit-image

Open prateek9623 opened this issue 3 years ago • 1 comments

System information (version)
  • OpenCV => 4.5.4
  • Language=> python/cpp
  • Operating System / Platform => Windows
  • Compiler => MSVC 19.32.31332.0 I am trying to replicate PIL and scikit-image nearest-neighbor o/p in OpenCV but getting INTER_NEAREST o/p.
  • Original image: img temp

  • OpenCV INTER_NEAREST: temp1

 cv2.resize(x,(0,0),fx=0.5,fy=0.5,interpolation=cv2.INTER_NEAREST)
  • OpenCV INTER_NEAREST_EXACT: temp2
 cv2.resize(x,(0,0),fx=0.5,fy=0.5,interpolation=cv2.INTER_NEAREST)
  • PIL : temp3
x1=Image.fromarray(img)
x1.thumbnail((256,256),Image.Resampling.NEAREST) 
  • scikit-image : temp5
rescale(x,0.5,order=0,preserve_range=True, anti_aliasing=False) 

As it can be seen, OpenCV INTER_NEAREST and OpenCV INTER_NEAREST_EXACT are matching, which is not expected. image

The expected was that the OpenCV INTER_NEAREST_EXACT should match PIL and scikit-image o/p, but I am getting this difference: image

Issue submission checklist
  • [x] I report the issue, it's not a question
  • [x] I checked the problem with documentation, FAQ, open issues, forum.opencv.org, Stack Overflow, etc and have not found any solution
  • [x] I updated to the latest OpenCV version and the issue is still there
  • [x] There is reproducer code and related data files: videos, images, onnx, etc

prateek9623 avatar Jul 07 '22 04:07 prateek9623

@alalek hi, you marked this issue duplicate, can I know which is the original one?

prateek9623 avatar Jul 29 '22 05:07 prateek9623

older issue: https://github.com/opencv/opencv/issues/9096

dkurt avatar May 12 '23 10:05 dkurt

It can't be duplicate of #9096 since INTER_NEAREST_EXACT is a result of discussion in #9096. If there is an issue in INTER_NEAREST_EXACT, this is a new issue.

homm avatar May 15 '23 12:05 homm

@homm, thanks! Let me check again

dkurt avatar May 15 '23 12:05 dkurt

@homm, indeed, there is a bug with even sizes. Odd sizes seem produce correct results. For example, using an image from the issue with extra padded zeros:

import numpy as np
import cv2 as cv
from skimage.transform import rescale, resize

img = cv.imread("177693650-83d8d354-2aa7-4680-99f2-ce7206f0aacb.png", cv.IMREAD_GRAYSCALE)
img = np.pad(img, ((0, 1), (0, 1)))
cvOut_exact = cv.resize(img, dsize=(256, 256),interpolation=cv.INTER_NEAREST_EXACT)

from PIL import Image

outPIL = Image.fromarray(img)
outPIL.thumbnail((256,256),Image.Resampling.NEAREST)
outPIL = np.array(outPIL)
print('OCV/PIL diff:', np.max(np.abs(cvOut_exact - outPIL)))

scikitOut = resize(img, output_shape=(256, 256), order=0, preserve_range=True, anti_aliasing=False)
print('OCV/Scikit diff:', np.max(np.abs(cvOut_exact.astype(np.int32) - scikitOut.astype(np.int32))))

Thanks for pushing it!

dkurt avatar May 17 '23 12:05 dkurt