首页 > 解决方案 > Python opencv在空白的白色画布上勾勒出黑色像素

问题描述

为了详细说明我的预期结果,我附上了一个 test.png 文件,以及我希望这个脚本做什么。

本质上,您必须以某种方式找到所有黑色像素以及如何找到它们的开始和停止位置。

然后我想放大它,可以这么说,我想将选定的像素(绿色方块中的内容)提取到它自己的图像中并保存。

我所有的图像都是黑白的,没有其他颜色。

原始图像

在此处输入图像描述

结果图像

在此处输入图像描述

从结果图像中提取

在此处输入图像描述

如果有人可以帮助我解决这个问题,将不胜感激!我尝试使用 Opencv Python 以某种方式找到黑色像素,但我所有的尝试都失败了。

标签: pythonimageopencvimage-processing

解决方案


这是在 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)


结果:

在此处输入图像描述


推荐阅读