Trim 拼接过程中的图像
Trim image during Stitching
我正在将多张图片拼接成一张。在中间步骤中,我得到如下图像:
图像完全没有必要从左边开始,右边有黑色区域。我想从这个不包含黑色区域的矩形图像中获取。也就是说,类似于:
有人可以建议我这样做的方法吗?
这是裁剪掉图像右侧多余黑色的一种方法:
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
输入:
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)
我正在将多张图片拼接成一张。在中间步骤中,我得到如下图像:
图像完全没有必要从左边开始,右边有黑色区域。我想从这个不包含黑色区域的矩形图像中获取。也就是说,类似于:
有人可以建议我这样做的方法吗?
这是裁剪掉图像右侧多余黑色的一种方法:
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
输入:
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)