python - Python OpenCV:从图像中删除边框
问题描述
假设我有这样的图像:
我想删除边框并得到这个:
所以完全相同的图像,没有边框。
我找到了一种“hacky”方法来找到外部轮廓并在其上画一条线......老实说这不是最好的方法,因为我需要调整线条的“粗细”,使其足够粗覆盖边界,但不要太厚,这样它就不会覆盖任何圆圈。
image
变量是您在上面看到的图像(已经灰度化、阈值化)。
cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
cv2.drawContours(image, cnts, -1, 0, 15) # 15 is the right thickness for this image, but might not be for other ones...
结果是上面的第二张图。效果很好,但不适用于所有图像(因为厚度不同)。有一个更好的方法吗?
解决方案
这就是我在评论中的意思......填充所有像左上角一样的黑色,并用白色连接到它,这样你想要的位现在完全被白色包围到边缘。然后用黑色填充所有白色并连接到左上角的东西。
#!/usr/local/bin/python3
import numpy as np
import cv2
from PIL import Image
# Load image and greyscale it
im = np.array(Image.open("framedcircles.jpg").convert('L'))
# Normalize and threshold image
im = cv2.normalize(im, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
res, im = cv2.threshold(im, 64, 255, cv2.THRESH_BINARY)
# Fill everything that is the same colour (black) as top-left corner with white
cv2.floodFill(im, None, (0,0), 255)
# Fill everything that is the same colour (white) as top-left corner with black
cv2.floodFill(im, None, (0,0), 0)
# Save result
Image.fromarray(im).save("result.png")
结果:
推荐阅读
- php - 无法在 codeigniter Session.php 中找到指定的类
- python - TFLiteConverter.from_frozen_graph 无法加载冻结图:ValueError
- firebase - 如何修复 Firestore SDK 在 iOS 上遇到“索引数据库服务器中遇到内部错误”错误?
- ios - 来自 xcodebuild 的“Xcode 无法确定配置文件的类型”错误
- stata - “平方”数据集
- php - 使用 PHP 实现 OCR
- php - 如何在发送电子邮件之前将数据保存在 wordpress 中的自定义帖子类型中?
- javascript - 警告:列表中的每个孩子都应该有一个唯一的“关键”道具。检查元素时不显示关键道具
- excel - VBA 根据单元格值自动执行 Power Query
- java - 如何在属性上添加标称值?