python图像拼接去掉黑边
时间: 2023-05-12 13:07:07 浏览: 484
利用python图像裁剪
可以使用 OpenCV 库中的函数 cv2.copyMakeBorder() 来去掉黑边,具体实现可以参考以下代码:
import cv2
def remove_black_border(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
x, y, w, h = cv2.boundingRect(cnt)
return img[y:y+h, x:x+w]
def merge_images(images):
rows = len(images)
cols = len(images[0])
height, width, channels = images[0][0].shape
merged = [[None] * cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
merged[i][j] = remove_black_border(images[i][j])
return cv2.vconcat([cv2.hconcat(merged[i]) for i in range(rows)])
images = [[cv2.imread(f'img_{i}_{j}.jpg') for j in range(3)] for i in range(3)]
merged = merge_images(images)
cv2.imwrite('merged.jpg', merged)
这段代码可以将 3x3 的图片拼接成一张大图,并去掉黑边。
阅读全文