要解决边框超出轮廓的问题,可以使用以下方法:
方法1:调整边框大小
import cv2
# 读取图像
image = cv2.imread("image.jpg")
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray, 50, 150)
# 查找轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 创建一个与原始图像大小相同的边框图像
border = np.zeros_like(image, dtype=np.uint8)
# 绘制边框
cv2.drawContours(border, contours, -1, (0, 255, 0), 2)
# 调整边框大小
x, y, w, h = cv2.boundingRect(contours[0])
border = border[y:y+h, x:x+w]
# 显示结果
cv2.imshow("Border", border)
cv2.waitKey(0)
cv2.destroyAllWindows()
方法2:使用掩膜
import cv2
import numpy as np
# 读取图像
image = cv2.imread("image.jpg")
# 转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray, 50, 150)
# 查找轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 创建一个与原始图像大小相同的掩膜
mask = np.zeros_like(gray, dtype=np.uint8)
# 绘制轮廓
cv2.drawContours(mask, contours, -1, 255, -1)
# 将掩膜应用于原始图像
result = cv2.bitwise_and(image, image, mask=mask)
# 显示结果
cv2.imshow("Result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
通过调整边框大小或使用掩膜,可以确保边框不超出轮廓。
上一篇:边框超出了div元素