我正在尝试裁剪这样的图像:
根据图像内的蓝色边框,使其具有类似这样的输出:
使裁剪后的图像包含边框内的整个图像。我看过类似的帖子,并考虑过使用 cv2.findContours,但在将图像传递给 findContours 函数之前,我一直在努力解决如何处理图像的问题。不知道是否应该应用阈值?任何帮助将不胜感激。
最佳答案
这是在 Python/OpenCV 中实现此目的的一种方法,即对蓝色进行阈值处理,然后找到白色的最小和最大边界。此方法假设蓝色框是与 X 和 Y 图像轴对齐的矩形。
输入:
import cv2
import numpy as np
# load image
img = cv2.imread("blue_box.jpg")
# get color bounds of blue box
lower =(230,150,60) # lower bound for each channel
upper = (255,190,100) # upper bound for each channel
# create the mask
mask = cv2.inRange(img, lower, upper)
# get bounds of white pixels
white = np.where(mask==255)
xmin, ymin, xmax, ymax = np.min(white[1]), np.min(white[0]), np.max(white[1]), np.max(white[0])
print(xmin,xmax,ymin,ymax)
# crop the image at the bounds
crop = img[ymin:ymax, xmin:xmax]
hh, ww = crop.shape[:2]
# write result to disk
cv2.imwrite("blue_box_mask.jpg", mask)
cv2.imwrite("blue_box_cropped.jpg", crop)
# display it
cv2.imshow("mask", mask)
cv2.imshow("crop", crop)
cv2.waitKey(0)
阈值图像:
裁剪后的图像:
关于python - 根据图像 python 内的边框裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64034464/