python - Python opencv在空白的白色画布上勾勒出黑色像素
问题描述
为了详细说明我的预期结果,我附上了一个 test.png 文件,以及我希望这个脚本做什么。
本质上,您必须以某种方式找到所有黑色像素以及如何找到它们的开始和停止位置。
然后我想放大它,可以这么说,我想将选定的像素(绿色方块中的内容)提取到它自己的图像中并保存。
我所有的图像都是黑白的,没有其他颜色。
原始图像
结果图像
从结果图像中提取
如果有人可以帮助我解决这个问题,将不胜感激!我尝试使用 Opencv Python 以某种方式找到黑色像素,但我所有的尝试都失败了。
解决方案
这是在 Python/OpenCV 中执行此操作的一种方法。
- 读取输入
- 转换为灰色
- 反转极性(轮廓区域需要为白色)
- 临界点
- 获取轮廓
- 获取边界框
- 根据边界框裁剪输入中的区域
- 保存到磁盘
输入:
import cv2
import numpy as np
# read image
img = cv2.imread("black_pixels.png")
# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# invert polarity
gray = 255 - gray
# do adaptive threshold on gray image
thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)[1]
# Get contours
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
i = 1
for c in cnts:
# create white image
result = np.full_like(img, (255,255,255))
# get bounding box
x,y,w,h = cv2.boundingRect(c)
# crop region of img using bounding box
region = img[y:y+h, x:x+w]
# save region to new image
cv2.imwrite("black_region_{0}.png".format(i), region)
i = i + 1
# display it
cv2.imshow("IMAGE", img)
cv2.imshow("GRAY", gray)
cv2.imshow("THRESHOLD", thresh)
cv2.waitKey(0)
结果:
推荐阅读
- java - DTO有@NotNull时,用ModelMapper映射不抛出异常?
- c++ - 提升多线程异常
- ansible - 如何将变量传递给 Jinja2 2.11.x 包含上下文?
- python-3.x - 使用 google docs API 添加制表位的正确方法是什么
- javascript - 将txt转换为值数组
- javascript - 如何在免费的云平台上部署 HTML 代码?
- java - 在 Recyclerview 中显示来自 Firebase 的数据,按用户名过滤 - 如何?
- android - 从 git 导入项目时创建的重复文件
- javascript - javascript中难以理解的对象重新分配
- pip - Win10 Python 3.8.1 64bit 安装 spaCy 的构建依赖项失败