![](/img/trans.png)
[英]How to find and crop words into individual images with Python OpenCV?
[英]How to find individual numbers in an image with Python OpenCV?
对图像中的图形进行分割和检测,主要思想如下:
cv2.cvtColor()
将图像转换为灰度cv2.GaussianBlur()
模糊图像cv2.Canny()
查找边缘cv2.findContours()
imutils.contours.sort_contours()
排序,以确保当我们遍历轮廓时,它们的顺序正确cv2.boundingRect()
获取边界矩形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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.