我正在尝试拍摄车牌的图像,以便随后可以进行一些图像处理以在车牌周围绘制轮廓,然后可以使用该图像扭曲透视图,然后在其上查看车牌正面。不幸的是,我在尝试围绕已处理的图像绘制轮廓时遇到错误。具体来说,我收到一个Invalid shape (4, 1, 2) for the image data
错误。我不太确定如何解决该问题,因为我知道我处理的所有其他图像都很好。只是当我尝试绘制轮廓时,出现了问题。
import cv2
import numpy as np
from matplotlib import pyplot as plt
kernel = np.ones((3,3))
image = cv2.imread('NoPlate0.jpg')
def getContours(img):
biggest = np.array([])
maxArea = 0
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv2.contourArea(cnt)
if area > 500:
cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt,0.02*peri, True)
if area > maxArea and len(approx) == 4:
biggest = approx
maxArea = area
return biggest
imgGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray,(5,5),1)
imgCanny = cv2.Canny(imgBlur,150,200)
imgDial = cv2.dilate(imgCanny,kernel,iterations=2)
imgThres = cv2.erode(imgDial,kernel,iterations=2)
imgContour = image.copy()
titles = ['original', 'Blur', 'Canny', 'Dialte', 'Threshold', 'Contours' ]
images = [image, imgBlur, imgCanny, imgDial, imgThres, getContours(imgThres)]
for i in range(6):
plt.subplot(3, 3, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.show()
我得到的确切错误是:
TypeError: Invalid shape (4, 1, 2) for image data
我正在使用以下图像作为输入:
您的函数仅返回沿轮廓的实际点,然后尝试在其上调用plt.imshow
。这就是为什么您会收到此错误的原因。您需要做的是将此轮廓与cv2.drawContour
配合使用以获取所需的内容。在这种情况下,我们应该重组getContours
函数,使其返回坐标(以便以后使用)和在图像本身上绘制的实际轮廓。不必将imgContour
进行变异并将其视为全局变量,而只需绘制一次该图像,该图像将是循环中找到的最大轮廓:
您需要将biggest
返回的getContours()
重塑为(4,2)。而且,如果您想要变形的图像,则需要导入imutils。因此,要解决您的问题,请执行以下操作: