Cropping overlaps in merged image

I want to switch to OpenCV from other software. To create a 3D image, I align 2 images in the Y axis and in rotation, but leaving the X axis alone, merge them, then crop the overlaps. I have some code from ChatGPT which successfully aligns the two images, but the cropping code only fixes the X axis The code looks reasonable to me, but I’m a newbie to this.
[edit] It doesn’t always fix the X axis either.

# input images are imageL and imageRaligned (same size)

# Determine the bounding box for the overlap
height, width = imageL.shape[:2]

# Calculate cropping margins (adjust as needed for accuracy)
x_min = max(0, int(matrix[0, 2]))
y_min = max(0, int(matrix[1, 2]))

x_max = width - x_min
y_max = height - y_min

# Crop both images to the overlapping region
imageLcrop = imageL[y_min:y_max, x_min:x_max]
imageRcrop = imageRaligned[y_min:y_max, x_min:x_max]

I don’t think the ChatGPT code is doing much. This is what I need to do:
To start with the bottom of the image: on the merged image I need to find the left-image’s bottom-left corner, left-image’s bottom-right, then the right-image’s bottom-left and bottom-right. Then compare them to find which is the highest up the merged image and use that figure to crop it off below that level.
Then repeat for the top and both sides. I imagine this has been done before - is there somewhere I can look for existing code?

I think my second post is wrong, I need to find the four points on the merged image.

The end result would be to crop final images to the overlapping region like this:
image-crop = image[y_min:y_max, x_min:x_max]