python - 根据图像 python 内的边框裁剪图像

标签 python opencv image-processing

我正在尝试裁剪这样的图像:

image to crop

根据图像内的蓝色边框,使其具有类似这样的输出:

Desired crop

使裁剪后的图像包含边框内的整个图像。我看过类似的帖子,并考虑过使用 cv2.findContours,但在将图像传递给 findContours 函数之前,我一直在努力解决如何处理图像的问题。不知道是否应该应用阈值?任何帮助将不胜感激。

最佳答案

这是在 Python/OpenCV 中实现此目的的一种方法,即对蓝色进行阈值处理,然后找到白色的最小和最大边界。此方法假设蓝色框是与 X 和 Y 图像轴对齐的矩形。

输入:

enter image description here

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)

阈值图像:

enter image description here

裁剪后的图像:

enter image description here

关于python - 根据图像 python 内的边框裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64034464/

相关文章:

python - Plotly:如何使用 plotly.graph_objects 制作由变量着色的折线图?

python - 如何将 cv2.frames 发送到浏览器

c# - 相机旋转 SolvePnp

python - 如何从 scipy imsave 函数中删除标准化

image-processing - 高斯模糊和 FFT

python - 如何检查 mongo ObjectID 在 python 中是否有效?

opencv - 如何修改openCV源代码?

opencv - "Could not find a version that satisfies the requirement opencv-python"

opencv - 我怎么知道使用 KCF 跟踪器跟踪丢失

python - 安装tinymce后Django TypeError