10

I am working with OpenCV 3.1 and with Python.

My problem comes when I try to deskew (fix the tilt of) an image with text. I am using cv2.warpPerspective to make it possible, but the image loses a lot of quality. You can see here the original part of the image:

image without smooth

and then, here, the "rotated" image:

image with smooth

it is like smoothed.

I was using morphological transformation like:

kernel = np.ones((2, 2), np.uint8)
blur_image = cv2.erode(tresh, kernel, iterations=1)

and

white_mask2 = cv2.morphologyEx(white_mask2, cv2.MORPH_OPEN, kernel)

to see if it improves something, but nothing.

I saw this example here in SO, but those guys had the same problem: enter image description here and enter image description here

So, I don't have idea what can I do. Maybe there is a way to not losing the quality of the image, or, there's another method to rotate the image without quality lost. I know this method:

root_mat = cv2.getRotationMatrix2D(to_rotate_center, angle, 1.0)
result = cv2.warpAffine(to_rotate, root_mat, to_rotate.shape, flags=cv2.INTER_LINEAR)

But it doesn't work for me, as I have to rotate every rectangle here:

enter image description here

and not the whole image. It means, the best way I found to do it, was warpPerspective, and it works fine, but with quality loss. I would appreciate an advice to avoid the quality lost.

Community
  • 1
  • 1
Chuck Aguilar
  • 1,998
  • 1
  • 27
  • 50

1 Answers1

14

The problem is related to the interpolation required by the warping. If you don't want things to appear smoother, you should switch from default interpolation method, which is INTER_LINEAR to another one, such as INTER_NEAREST. It would help you with the sharpness of the edges.

Try flags=cv2.INTER_NEAREST on your warp call, be it warpAffine() or warpPerspective().

Interpolation flags are listed here.

enum InterpolationFlags { 
    INTER_NEAREST = 0, 
    INTER_LINEAR = 1, 
    INTER_CUBIC = 2, 
    INTER_AREA = 3, 
    INTER_LANCZOS4 = 4, 
    INTER_MAX = 7, 
    WARP_FILL_OUTLIERS = 8, 
    WARP_INVERSE_MAP = 16 
}
Berriel
  • 12,659
  • 4
  • 43
  • 67
  • 1
    Beautiful man! Thank you :) The problem was with the cv2.INTER_LINEAR. – Chuck Aguilar Sep 07 '16 at 14:36
  • For more background info about the differences between these interpolation methods, check out https://en.wikipedia.org/wiki/Comparison_gallery_of_image_scaling_algorithms and https://tanalin.com/en/articles/integer-scaling/ – n0099 Feb 14 '23 at 17:41