我有500x500px的图像,每个图像都有一个或多个手写数字绘制在TKinter画布上,并保存到一个PNG文件(example)。
这些数字最终都被提供给一个接受28x28px图像的数字识别器神经网络(为此,我使用tensorflow)。
如果图像只有一个数字(example),我不需要分割这些数字。图像大小调整为28x28px,并馈送到数字识别器(example after resizing)。在这种情况下,我有很好的识别准确率。
当图像有一个以上的数字时,我的问题就出现了。在本例中,我对各个数字进行了分段,并将每个数字保存在一个单独的图像文件中。这些图像中的每一个都会被调整大小并输入到数字识别器中,但在这种情况下,我的准确率非常高。
准确率的下降是由于调整大小的分割图像的特征和我训练神经网络的图像的特征的差异,例如图像的边缘/填充和数字本身的厚度。
当我分割一个数字并将其保存到一个单独的图像文件时,这个新文件没有填充/边距(example)。在将其大小调整为28x28px后,我得到了一个比正常值厚得多的数字,但没有填充/边距(example)。它看起来有点扭曲。这与我用来训练神经网络的数字图像不同。这就是为什么我预测数字的准确率很低。
为了解决这个问题,我希望保留最终28x28px图像中的填充/边距和厚度以及分割后的数字,该图像将提供给数字识别器。我的想法是,在保存分割后的图像(在重塑它之前),将它放在一个500x500px的白色正方形的中心。因此,这个分割的数字几乎与我在原始图像中只有1个手写数字的情况相同,在重塑为28x28后,我将保留页边距和粗细。我该如何实现这个想法呢?
我用来分割数字的代码(credits to Devashish Prasad):
# import the necessary packages
import numpy as np
import cv2
import imutils
# load the image, convert it to grayscale, and blur it to remove noise
image = cv2.imread("sample1.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
# threshold the image
ret,thresh1 = cv2.threshold(gray ,127,255,cv2.THRESH_BINARY_INV)
# dilate the white portions
dilate = cv2.dilate(thresh1, None, iterations=2)
# find contours in the image
cnts = cv2.findContours(dilate.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
orig = image.copy()
i = 0
for cnt in cnts:
# Check the area of contour, if it is very small ignore it
if(cv2.contourArea(cnt) < 100):
continue
# Filtered countours are detected
x,y,w,h = cv2.boundingRect(cnt)
# Taking ROI of the cotour
roi = image[y:y+h, x:x+w]
# Mark them on the image if you want
cv2.rectangle(orig,(x,y),(x+w,y+h),(0,255,0),2)
# Save your contours or characters
cv2.imwrite("roi" + str(i) + ".png", roi)
i = i + 1
cv2.imshow("Image", orig)
cv2.waitKey(0)发布于 2020-06-15 06:54:55
在我的一个项目中,我需要一个类似的东西。我没有将裁剪后的图像粘贴到500 x 500白色背景的中心,而是填充了图像的周围,直到大小达到500 x 500,如下所示:
ih, iw = 500, 500 # <-- The desired output height and width
h, w = image.shape
out_image = cv2.copyMakeBorder(image, int((ih - h / 2)), int((ih - h / 2)), int((iw - w / 2)), int((iw - w / 2)), cv2.BORDER_CONSTANT, value=255)对我来说,这似乎更容易。希望能有所帮助。
https://stackoverflow.com/questions/62312143
复制相似问题