I know that this issue has other posts, but none of them helped me:
import cv2 as cv
import numpy as np
widthImg = 640
heightImg = 480
frameWidth = 640
frameHeight = 480
cap = cv.VideoCapture(2)
cap.set(3, widthImg)
cap.set(4, heightImg)
cap.set(10,150)
def preProcessing(img):
imgGray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
imgBlur = cv.GaussianBlur(imgGray,(5,5),1)
imgCanny = cv.Canny(imgBlur,200,200)
kernel = np.ones((5,5))
imgDial = cv.dilate(imgCanny,kernel,iterations=2)
imgThres = cv.erode(imgDial,kernel,iterations=1)
return imgThres
def getContours(img):
biggest = np.array([])
maxArea = 0
contours,hierarchy = cv.findContours(img,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_NONE)
for cnt in contours:
area = cv.contourArea(cnt)
if area>5000:
#cv.drawContours(imgContour, cnt, -1, (255,0,0), 3)
peri = cv.arcLength(cnt,True)
approx = cv.approxPolyDP(cnt,0.02*peri,True)
if area >maxArea and len(approx) == 4:
biggest = approx
maxArea = area
cv.drawContours(imgContour, biggest, -1, (255, 0, 0), 20)
return biggest
def getWarp(img,biggest):
pts1 = np.array(biggest,np.float32)
pts2 = np.array([[0, 0], [widthImg, 0], [0, heightImg], [widthImg, heightImg]],np.float32)
matrix = cv.getPerspectiveTransform(pts1, pts2)
imgOutput = cv.warpPerspective(img, matrix, (widthImg, heightImg))
return imgOutput
while True:
success, img = cap.read()
img = cv.resize(img,(widthImg,heightImg))
imgContour = img.copy()
imgThres = preProcessing(img)
biggest = getContours(imgThres)
print(biggest)
imgWarped = getWarp(img,biggest)
cv.imshow("Result", imgWarped)
if cv.waitKey(1) & 0xFF == ord('q'):
break
So this is my code in Pycharm. I know that the problem came when I use 'biggest' at the 44 line (pts1 = np.array(biggest,np.float32) I know that if I write 4 two-dimensional points instead 'biggest' it will work. But in a video that i'm following, the programmer used 'biggest' without any problem. I know that it already said that 'biggest' has 4 points (in def getContours(img):). I don't know why is not working in my case and in others yes.
And this is the error message that I get:
Traceback (most recent call last):
File "/home/nvidia/PycharmProjects/OpencvPython/Resources/Project2.py", line 61, in <module>
imgWarped = getWarp(img,biggest)
File "/home/nvidia/PycharmProjects/OpencvPython/Resources/Project2.py", line 46, in getWarp
matrix = cv.getPerspectiveTransform(pts1, pts2)
cv2.error: OpenCV(4.5.1) /tmp/pip-req-build-q3gzfcr4/opencv/modules/imgproc/src/imgwarp.cpp:3392: error: (-215:Assertion failed) src.checkVector(2, CV_32F) == 4 && dst.checkVector(2, CV_32F) == 4 in function 'getPerspectiveTransform'
Sorry if this is a stupid issue but I'm new in python programming and I spend a couple of hours trying to solve it.