Given binarized image, warpAffine() returns non-binarized image

I’m passing a binarized grayscale image to warpAffine(), and I’m surprised to find that it returns a NON-binarized grayscale image. In other words, I pass in black-and-white, and I get back gray. Why would rotating an image have any effect on its color values?

In case it matters, I’m using OpenCV version 4.5.something, in Python.

import cv2

img = cv2.imread("any_image.jpg", cv2.IMREAD_GRAYSCALE)
thresh, img_bin = cv2.threshold(img, 42, 255, cv2.THRESH_BINARY)   # 42 is arbitrary

print(f"Binarized image contains {cv2.countNonZero(cv2.inRange(img_bin, 1, 254))} gray values.")

height, width = img.shape[:2]
image_center = (width/2, height/2)
degrees = 5    # number of degrees doesn't matter

rotation_matrix = cv2.getRotationMatrix2D(image_center, degrees, scale=1)
rotated_img = cv2.warpAffine(img_bin, rotation_matrix, (width, height))

print(f"Image returned by warpAffine() contains {cv2.countNonZero(cv2.inRange(rotated_img, 1, 254))} gray values. Why?")

For my particular image file, the above code prints this:
Binarized image contains 0 gray values.
Image returned by warpAffine() contains 11631 gray values. Why?

the default is INTER_LINEAR. that means interpolation.

why do you expect that to not give you intermediate values?

anyway, you should threshold after the warp.


Ah, that makes sense. And now that you’ve pointed that out, I find that if I pass INTER_NEAREST instead of the default INTER_LINEAR, the result of warpAffine() is what I was hoping for (all 0’s and 255’s, no gray). Thank you for your help!