python - 拼接时修剪图像

标签 python opencv image-processing computer-vision panoramas

我正在将多张图像拼接成一张。在一个中间步骤中,我得到一个像这样的图像:

enter image description here

图像从左开始并在右侧具有黑色区域是完全没有必要的。我要从此图像中获取一个不包含黑色区域的矩形图像。也就是说,类似:

enter image description here

有人可以建议我这样做吗?

最佳答案

这是一种裁剪图像右侧多余黑色的方法:

Read the image

Convert to grayscale

Threshold

Apply closing and opening morphology to remove small black and white spots.

Get the surrounding contour

Crop the contour

Save the result

输入:

enter image description here
import cv2
import numpy as np

# read image
img = cv2.imread('road.jpg')

# convert to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold
_,thresh = cv2.threshold(gray,5,255,cv2.THRESH_BINARY)

# apply close and open morphology to fill tiny black and white holes
kernel = np.ones((5,5), np.uint8)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)

# get contours (presumably just one around the nonzero pixels) 
# then crop it to bounding rectangle
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
for cntr in contours:
    x,y,w,h = cv2.boundingRect(cntr)
    crop = img[y:y+h,x:x+w]
    # show cropped image
    cv2.imshow("CROP", crop)

cv2.waitKey(0)
cv2.destroyAllWindows()

# save cropped image
cv2.imwrite('road_crop.png',crop)

enter image description here

关于python - 拼接时修剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58167717/

相关文章:

php - 我的双线性插值算法有什么问题?

python - 如何使用 python 绘制从 RTL SDR 接收到的信号的实时图?

python - OpenCV 简单 Blob 检测器未检测到所有 Blob

python - 从树莓派上的网络摄像头获取 Python 输入?

python - 计算汽车 OpenCV + Python 问题

image-processing - 形状检测 - TensorFlow

python - Django 通过多个过滤器过滤,检查某些条件

Python 和 Pandas : Find a dict within a list according to a key's value

python imaplib 仅返回 exchange 2013 的一半消息

使用 imread 将 OpenCV 图像从 RGB 转换为灰度,结果不佳