2

My full code:

import cv2 as cv
import numpy as np


cap = cv.VideoCapture(0 + cv.CAP_DSHOW)
imgTarget = cv.imread('photos\TargetImage.jpg') #bu resmimiz
myVid = cv.VideoCapture('photos\video.mp4')


detection = False
frameCounter = 0
imgVideo = cap.read()
success, imgVideo = myVid.read()
hT,wT,cT = imgTarget.shape #burada resmimizin yüksekliğini, kalınlığını genişliğini falan alıyoruz.
'''while myVid.isOpened():
    success, Video = myVid.read()
    if success:
        Video = cv.resize(Video, (wT, hT))'''

#burada key points yani böyle önemli bölgeler, köşeler gibi yerleri beliriliyoruz.
orb = cv.ORB_create(nfeatures=1000)
kp1, des1 = orb.detectAndCompute(imgTarget,None)

while True: #burada webcam ile fotoğrafları birleştircez.
 

    sucess,imgWebcam = cap.read()
    imgAug = imgWebcam.copy()
    #burada key points yani böyle önemli bölgeler, köşeler gibi yerleri beliriliyoruz.
    kp2, des2 = orb.detectAndCompute(imgWebcam, None)#imgwebcami myvid yapıp değiştir o zaman oldu .d tek seferliktir belki?
    # imgWebcam = cv2.drawKeypoints(imgWebcam, kp2, None)
 
    if detection == False:
        myVid.set(cv.CAP_PROP_POS_FRAMES,0)
        frameCounter = 0
    else:
        if frameCounter == myVid.get(cv.CAP_PROP_FRAME_COUNT):
            myVid.set(cv.CAP_PROP_POS_FRAMES, 0)
            frameCounter = 0
        success, imgVideo = myVid.read()
        imgVideo = cv.resize(imgVideo, (wT, hT))
 
    #burada ise matches yani webcam resmi ile fotoğrafımız arasındaki benzerlikleri alıyoruz.
    bf = cv.BFMatcher()
    matches = bf.knnMatch(des1,des2,k=2)
    good =[]
    for m,n in matches:
        if m.distance < 0.75 *n.distance:
            good.append(m)
    print(len(good))
    imgFeatures = cv.drawMatches(imgTarget,kp1,imgWebcam,kp2,good,None,flags=2)
 
    if len(good) > 20: #burada eğer anahtar bölgelerimiz 20 den fazla şekilde uyuşuyorsa, tanımlama(detection) tamamlanmış oluyor.
        detection = True
        srcPts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
        dstPts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
        matrix, mask = cv.findHomography(srcPts,dstPts,cv.RANSAC,5)
        print(matrix)

        #eşleşine resmin etrafını çiziyoruz
        pts = np.float32([[0,0],[0,hT],[wT,hT],[wT,0]]).reshape(-1,1,2)
        dst = cv.perspectiveTransform(pts,matrix)
        img2 = cv.polylines(imgWebcam,[np.int32(dst)],True,(255,0,255),3)

        #burada videomuzu, webcam resmimiz ile aynı boyuta getiriyoruz.
        imgWarp = cv.warpPerspective(imgVideo,matrix, (imgWebcam.shape[1],imgWebcam.shape[0]))

. . . . . Hi guys, I am doing a project. And in my code I tried to use warpPerspective parameter. But in that line it gives the error of:

error: OpenCV(4.0.1) C:\ci\opencv-suite_1573470242804\work\modules\imgproc\src\imgwarp.cpp:2903: error: (-215:Assertion failed) _src.total() > 0 in function 'cv::warpPerspective'

And this is my related code of error:

imgWarp = cv.warpPerspective(imgVideo,matrix, (imgWebcam.shape[1],imgWebcam.shape[0]))

I also copied my all code to top of my page because it can be needed.

Is there any problem about my webcam? But it works in other codes, or in applications also. Why that this error occures and how can I solve it?

I am waiting your help... Any suggestions will be juch a big benefit to solve this issue.

1 Answers1

2

Let me start with a minor change with your code.

When you initialized using \ separator, your code will work only for Windows.

imgTarget = cv.imread('photos\TargetImage.jpg') #bu resmimiz
myVid = cv.VideoCapture('photos\video.mp4')

If you use os.path's sep, it will work on all OS.

from os.path import sep

imgTarget = cv.imread('photos' + sep + 'TargetImage.jpg') #bu resmimiz
myVid = cv.VideoCapture('photos' + sep + 'video.mp4')

I would like to suggest you to use the default resolution and initialize your cap variable as:

cap = cv.VideoCapture(0)

You can also display the imgWarp using imshow

cv.imshow("imgWarp", imgWarp)
cv.waitKey(0)

An example output:

enter image description here

Code:


import cv2 as cv
import numpy as np

from os.path import sep

cap = cv.VideoCapture(0)
imgTarget = cv.imread('photos' + sep + 'TargetImage.jpg')  # bu resmimiz
myVid = cv.VideoCapture('photos' + sep + 'video.mp4')

detection = False
frameCounter = 0
# imgVideo = cap.read()
success, imgVideo = myVid.read()
hT, wT, cT = imgTarget.shape  # burada resmimizin yüksekliğini, kalınlığını genişliğini falan alıyoruz.
'''while myVid.isOpened():
    success, Video = myVid.read()
    if success:
        Video = cv.resize(Video, (wT, hT))'''

# burada key points yani böyle önemli bölgeler, köşeler gibi yerleri beliriliyoruz.
orb = cv.ORB_create(nfeatures=1000)
kp1, des1 = orb.detectAndCompute(imgTarget, None)

while myVid.isOpened():  # burada webcam ile fotoğrafları birleştircez.
    sucess, imgWebcam = cap.read()
    imgAug = imgWebcam.copy()
    # burada key points yani böyle önemli bölgeler, köşeler gibi yerleri beliriliyoruz.
    kp2, des2 = orb.detectAndCompute(imgWebcam,
                                     None)  # imgwebcami myvid yapıp değiştir o zaman oldu .d tek seferliktir belki?
    # imgWebcam = cv2.drawKeypoints(imgWebcam, kp2, None)

    if detection == False:
        myVid.set(cv.CAP_PROP_POS_FRAMES, 0)
        frameCounter = 0
    else:
        if frameCounter == myVid.get(cv.CAP_PROP_FRAME_COUNT):
            myVid.set(cv.CAP_PROP_POS_FRAMES, 0)
            frameCounter = 0
        success, imgVideo = myVid.read()
        imgVideo = cv.resize(imgVideo, (wT, hT))

    # burada ise matches yani webcam resmi ile fotoğrafımız arasındaki benzerlikleri alıyoruz.
    bf = cv.BFMatcher()
    matches = bf.knnMatch(des1, des2, k=2)
    good = []
    for m, n in matches:
        if m.distance < 0.75 * n.distance:
            good.append(m)
    print(len(good))
    imgFeatures = cv.drawMatches(imgTarget, kp1, imgWebcam, kp2, good, None, flags=2)

    if len(good) > 20:  # burada eğer anahtar bölgelerimiz 20 den fazla şekilde uyuşuyorsa, tanımlama(detection) tamamlanmış oluyor.
        detection = True
        srcPts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
        dstPts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
        matrix, mask = cv.findHomography(srcPts, dstPts, cv.RANSAC, 5)
        print(matrix)

        # eşleşine resmin etrafını çiziyoruz
        pts = np.float32([[0, 0], [0, hT], [wT, hT], [wT, 0]]).reshape(-1, 1, 2)
        dst = cv.perspectiveTransform(pts, matrix)
        img2 = cv.polylines(imgWebcam, [np.int32(dst)], True, (255, 0, 255), 3)

        # burada videomuzu, webcam resmimiz ile aynı boyuta getiriyoruz.
        imgWarp = cv.warpPerspective(imgVideo, matrix, (imgWebcam.shape[1], imgWebcam.shape[0]))
        cv.imshow("imgWarp", imgWarp)
        cv.waitKey(0)

Is there any problem about my webcam? But it works in other codes, or in applications also. Why that this error occures and how can I solve it?

If you want to connect your default webcam, usually you initialized as:

myVid = cv.VideoCapture(0)

If you want to connect to your external-device you can use 1, 2, etc.

Ahmet
  • 7,527
  • 3
  • 23
  • 47
  • Thanks for replying I will try it soon, then I will back here – Ö. ALP EREN GÜL Jan 28 '21 at 07:00
  • hi again, can I ask same error but in a different code by edditing my question? I changed some of codes(not so much) and give same error. After I edit my question would you look again? Or should I open a new question – Ö. ALP EREN GÜL Feb 04 '21 at 14:39
  • Its up to you, but if I were you I would ask a new question, since if you add a new code it would become confusing. Therefore I would suggest posting a new question, but of course you'll decide – Ahmet Feb 04 '21 at 16:09
  • yes you are right but a small question: Why GIF images does not has shape in opencv? – Ö. ALP EREN GÜL Feb 04 '21 at 18:17
  • Opencv is not supporting gif images. Most probably it returns None. You need to convert it to the supported formats, like png, jpeg, jpg, etc. – Ahmet Feb 04 '21 at 18:38
  • I know I asked lots of questions but if you have time or if you want I just ask for you for this new question ===> https://stackoverflow.com/questions/66076212/opencv-overlay-a-video-on-webcam – Ö. ALP EREN GÜL Feb 06 '21 at 11:15
  • You want to learn therefore thats ok. I answered the question. – Ahmet Feb 06 '21 at 13:32
  • Sir Can I ask another thing? I couldnt solve it. Please help me to solve.... link ===> https://stackoverflow.com/questions/66292414/opencv-curve-the-top-of-line-to-position-of-detected-object?noredirect=1#comment117201322_66292414 – Ö. ALP EREN GÜL Feb 20 '21 at 16:08