![](/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.