以下是Python代码实现:

import cv2

# 读入原始图片
img = cv2.imread('original_image.jpg')

# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 二值化处理
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# 计算边框大小
top, bottom, left, right = 0, 0, 0, 0

# 计算顶部边框大小
for i in range(thresh.shape[0]):
    if cv2.mean(thresh[i])[0] == 255:
        top += 1
    else:
        break

# 计算底部边框大小
for i in range(thresh.shape[0]-1, -1, -1):
    if cv2.mean(thresh[i])[0] == 255:
        bottom += 1
    else:
        break

# 计算左侧边框大小
for i in range(thresh.shape[1]):
    if cv2.mean(thresh[:, i])[0] == 255:
        left += 1
    else:
        break

# 计算右侧边框大小
for i in range(thresh.shape[1]-1, -1, -1):
    if cv2.mean(thresh[:, i])[0] == 255:
        right += 1
    else:
        break

# 输出边框大小
print('Top border:', top)
print('Bottom border:', bottom)
print('Left border:', left)
print('Right border:', right)

# 绘制边框
cv2.rectangle(img, (0, 0), (img.shape[1], img.shape[0]), (255, 255, 255), top)
cv2.rectangle(img, (0, 0), (img.shape[1], img.shape[0]), (255, 255, 255), bottom)
cv2.rectangle(img, (0, 0), (img.shape[1], img.shape[0]), (255, 255, 255), left)
cv2.rectangle(img, (0, 0), (img.shape[1], img.shape[0]), (255, 255, 255), right)

# 保存新图片
cv2.imwrite('new_image.jpg', img)

该代码首先读入原始图片,然后将其转换为灰度图像并进行二值化处理。接着,通过分别遍历每一行和每一列,计算出图像四周的白色边框大小。最后,使用cv2.rectangle函数在原始图片上绘制白色边框,并将新图片保存到文件中

opencv2中计算图像四周的白色边框大小并另存为新图片

原文地址: https://www.cveoy.top/t/topic/hucn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录