繁体   English   中英

如何使用 Python OpenCV 在图像中查找单个数字?

[英]How to find individual numbers in an image with Python OpenCV?

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

在此处输入图像描述

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

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

在此处输入图像描述

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

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

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

Canny 边缘检测

在此处输入图像描述

检测到的轮廓

在此处输入图像描述

裁剪和保存的 ROI

在此处输入图像描述

输出

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 and extract ROI
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:
    x,y,w,h = cv2.boundingRect(c)
    ROI = original[y:y+h, x:x+w]
    cv2.rectangle(image, (x,y), (x+w,y+h),(36, 255, 12), 3)
    cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
    ROI_number += 1

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

按照步骤:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM