Crop image with corrected distortion in OpenCV (Python)

I searched the answer in other posts and tried several ways to get it, but I did not find anything that could solve my problem. I am trying to correct the optical distortion of an image and get it, but now I want to crop the image to remove the curved black borders in the result image. So, in summary, this is my problem:

problem

I want to crop like this:

enter image description here

I tried to trim with the following code:

h,  w = corrected_img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(cameraMTX,distortionCoeffs,(w,h),1,(w,h))
x,y,w,h = roi
desired_result = corrected_img[y:y+h, x:x+w]

But, unfortunately, it roialways takes on value (0,0,0,0).

Can anyone help me?

Thanks in advance.

+4
source share
1 answer

void / , , . :

x1, y1, x2 y2, . :

import cv2
# Reads the image in grayscale
img = cv2.imread('Undistorted.jpg', 0)
h, w = img.shape
x1, x2, y1, y2 = (0,0,0,0)

# Color threshold of the void part
void_th = 10

# List of colors in the vertical an horizontal lines that cross the image in the middle
vertical = [img[i, int(w/2)] for i in range(h)]
horizontal = [img[int(h/2), i] for i in range(w)]

# Reverses both lists
vertical_rev = vertical[::-1]
horizontal_rev = horizontal[::-1]

# Looks when the change of color is done
for i in range(2,h):
    if vertical[i] > void_th and y1 == 0:
        y1 = i
    if vertical_rev[i] > void_th and y2 == 0:
        y2 = i
    if y1 != 0 and y2 != 0:
        break
for i in range(2,w):
    if horizontal[i] > void_th and x1 == 0:
        x1 = i
    if horizontal_rev[i] > void_th and x2 == 0:
        x2 = i
    if x1 != 0 and x2 != 0:
        break

desired_result = img[y1:h-y2, x1:w-x2]
cv2.imshow('Crop', desired_result)

, , , , (0 - , 255 - ). , , , . - :

: 2 - , .

, !

+5

Source: https://habr.com/ru/post/1663775/


All Articles