Search code examples
python-3.xopencvimage-rotation

OpenCV Rotation with warpAffine in Python Causes Erroneous Border


Check out this Python code:

degrees = 90
center  = (24, 24)

img     = np.ones((48,48,3)) * 255
mat     = cv2.getRotationMatrix2D(center, degrees, 1.0)
img     = cv2.warpAffine(img, mat, (48, 48))

My expectation is that a 3 channel, fully saturated, white square will be created and stored in img. After which, it'll be rotated by 90 degrees. Rotating a white square by 90 degrees should result in ... an indistinguishable white square. But when I:

plt.imshow(img)
plt.show(img)

I see an erroneous black border:

What gives

Is there any way to get warpAffine working as expected, i.e. rotate the image without an erroneous border? I've tried the following modifications to no avail:

center  = (23, 23)
center  = (24, 23)
center  = (23, 24)
center  = (25, 25)
center  = (24, 25)
center  = (25, 24)

Solution

  • You should be using the exact center of the image rather than the next closest thing. The rotation is slightly off center using (24,24).

    Since getRotationMatrix2D accepts a Point2f, you should be passing the center as (23.5,23.5), as it is the midway point between 0 and 47.