【问题标题】:How to find individual numbers in an image with Python OpenCV?如何检测图像中的单独数字?
【发布时间】:2019-09-10 23:09:39
【问题描述】:

我有一个类似于以下的图像。如图所示,我想分隔两个数字 74,因为我想为这两个对象分别设置一个边界框。

如何使用 OpenCV 做到这一点?我不知道,我怎么能这样做,并且正在考虑是否有某种方法可以使用 Sobel 运算符。唯一让我感到厌烦的就是得到 Sobel。

s = cv2.Sobel(img, cv2.CV_64F,1,0,ksize=5)

但不知道如何从这里开始。

【问题讨论】:

标签: python image opencv image-processing computer-vision


【解决方案1】:

按照以下步骤操作:

  1. 将图像转换为灰度。
  2. 使用阈值将图像转换为二进制图像,在您的问题中我认为adaptive gausian 将最有益于使用。
  3. 应用轮廓检测​​,然后您可以围绕轮廓制作边界框。

您可能需要根据大小或位置过滤轮廓。

【讨论】:

【解决方案2】:

对图像中的图形进行分割和检测,主要思路如下:

  1. 使用cv2.cvtColor()将图像转换为灰度
  2. cv2.GaussianBlur()模糊图像
  3. 使用cv2.Canny() 查找边缘
  4. 使用cv2.findContours() 查找轮廓并使用从左到右排序 imutils.contours.sort_contours() 确保当我们遍历轮廓时,它们的顺序正确
  5. 遍历每个轮廓
    • 使用cv2.boundingRect()获取边界矩形
    • 使用 Numpy 切片查找每个轮廓的 ROI
    • 使用cv2.rectangle()绘制边界框矩形

Canny 边缘检测

检测到的轮廓

裁剪和保存的 ROIs

输出

Contours Detected: 2

代码

import numpy as np
import cv2
from imutils import contours

# Load image, grayscale, Gaussian blur, Canny edge detection
image = cv2.imread("1.png")
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3,3), 0)
canny = cv2.Canny(blurred, 120, 255, 1)

# Find contours
contour_list = []
ROI_number = 0
cnts = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts, _ = contours.sort_contours(cnts, method="left-to-right")
for c in cnts:
    # Obtain bounding rectangle for each contour
    x,y,w,h = cv2.boundingRect(c)

    # Find ROI of the contour
    roi = image[y:y+h, x:x+w]

    # Draw bounding box rectangle, crop using Numpy slicing
    cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),3)
    ROI = original[y:y+h, x:x+w]
    cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
    contour_list.append(c)
    ROI_number += 1

print('Contours Detected: {}'.format(len(contour_list)))
cv2.imshow("image", image) 
cv2.imshow("canny", canny)
cv2.waitKey()

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2021-08-06
    • 2021-03-17
    相关资源
    最近更新 更多