python - 使用带有Python和OpenCV的Raspberry Pi和Android IP摄像机进行对象检测

标签 python opencv raspberry-pi3 ip-camera

这是我使用树莓派和Android Ip Camera进行对象检测的代码。在这里,我没有任何输出,代码也没有提供任何错误。有人可以找出错误所在吗?

import urllib.request
import cv2
import numpy as np
import datetime
import math

#global variables
width = 0
height = 0
EntranceCounter = 0
ExitCounter = 0
MinCountourArea = 3000  #Adjust ths value according to your usage
BinarizationThreshold = 70  #Adjust ths value according to your usage
OffsetRefLines = 150  #Adjust ths value according to your usage

#Check if an object in entering in monitored zone
def CheckEntranceLineCrossing(y, CoorYEntranceLine, CoorYExitLine):
  AbsDistance = abs(y - CoorYEntranceLine)  

  if ((AbsDistance <= 2) and (y < CoorYExitLine)):
                 return 1
  else:
                 return 0
#Check if an object in exitting from monitored zone
def CheckExitLineCrossing(y, CoorYEntranceLine, CoorYExitLine):
    AbsDistance = abs(y - CoorYExitLine)    

    if ((AbsDistance <= 2) and (y > CoorYEntranceLine)):
                   return 1
    else:

                   return 0
这是我用于从IP摄像机获取视频流的代码
ReferenceFrame = None

while True:
  camera=cv2.VideoCapture("http://192.168.1.6:8080/shot.jpg")
  camera.set(3,640)
  camera.set(4,480)
  (ret,Frame)=camera.read()
  height = np.size(Frame,0)
  width = np.size(Frame,1)

#if cannot grab a frame, this program ends here.
  if not ret:
    break
这是我用来显示行和框架以进行对象检测和对象计数的代码部分
#gray-scale convertion and Gaussian blur filter applying
    GrayFrame = cv2.cvtColor(Frame, cv2.COLOR_BGR2GRAY)
    GrayFrame = cv2.GaussianBlur(GrayFrame, (21, 21), 0)
    
    if ReferenceFrame is None:
        ReferenceFrame = GrayFrame
        continue

    #Background subtraction and image binarization
    FrameDelta = cv2.absdiff(ReferenceFrame, GrayFrame)
    FrameThresh = cv2.threshold(FrameDelta, BinarizationThreshold, 255, cv2.THRESH_BINARY)[1]
    
    #Dilate image and find all the contours
    FrameThresh = cv2.dilate(FrameThresh, None, iterations=2)
    _, cnts, _ = cv2.findContours(FrameThresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    QttyOfContours = 0

    #plot reference lines (entrance and exit lines) 
    CoorYEntranceLine = (height / 2)-OffsetRefLines
    CoorYExitLine = (height / 2)+OffsetRefLines
    cv2.line(Frame, (0,CoorYEntranceLine), (width,CoorYEntranceLine), (255, 0, 0), 2)
    cv2.line(Frame, (0,CoorYExitLine), (width,CoorYExitLine), (0, 0, 255), 2)


    #check all found countours
    for c in cnts:
        #if a contour has small area, it'll be ignored
        if cv2.contourArea(c) < MinCountourArea:
            continue

        QttyOfContours = QttyOfContours+1    

        #draw an rectangle "around" the object
        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(Frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

        #find object's centroid
        CoordXCentroid = (x+x+w)/2
        CoordYCentroid = (y+y+h)/2
        ObjectCentroid = (CoordXCentroid,CoordYCentroid)
        cv2.circle(Frame, ObjectCentroid, 1, (0, 0, 0), 5)
        
        if (CheckEntranceLineCrossing(CoordYCentroid,CoorYEntranceLine,CoorYExitLine)):
            EntranceCounter += 1

        if (CheckExitLineCrossing(CoordYCentroid,CoorYEntranceLine,CoorYExitLine)):  
            ExitCounter += 1

    print ("Total countours found: "+str(QttyOfContours))

    #Write entrance and exit counter values on frame and shows it
    cv2.putText(Frame, "Entrances: {}".format(str(EntranceCounter)), (10, 50),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (250, 0, 1), 2)
    cv2.putText(Frame, "Exits: {}".format(str(ExitCounter)), (10, 70),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)




   
  cv2.imshow('Salida',Frame)
  cv2.waitKey(1);

# When everything done, release the capture 
cap.release()
cv2.destroyAllWindows()

最佳答案

正确的代码

import numpy as np
import math

def nothing(x):
    pass
width=0
height=0
EntranceCounter = 0
OffsetRefLines = 150
ExitCounter = 0
BinarizationThreshold = 70
MinCountourArea = 3000

cap = cv2.VideoCapture(0);
path="http://192.168.1.6:8080/video"
cap.open(path)
ReferenceFrame = None

#Check if an object in entering in monitored zone
def CheckEntranceLineCrossing(y, CoorYEntranceLine, CoorYExitLine):
  AbsDistance = abs(y - CoorYEntranceLine)  

  if ((AbsDistance <= 2) and (y < CoorYExitLine)):
                 return 1
  else:
                 return 0

#Check if an object in exitting from monitored zone
def CheckExitLineCrossing(y, CoorYEntranceLine, CoorYExitLine):
    AbsDistance = abs(y - CoorYExitLine)    

    if ((AbsDistance <= 2) and (y > CoorYEntranceLine)):
                   return 1
    else:

                   return 0


#cv2.namedWindow("Tracking")
cv2.createTrackbar("LH", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LS", "Tracking", 0, 255, nothing)
cv2.createTrackbar("LV", "Tracking", 0, 255, nothing)
cv2.createTrackbar("UH", "Tracking", 255, 255, nothing)
cv2.createTrackbar("US", "Tracking", 255, 255, nothing)
cv2.createTrackbar("UV", "Tracking", 255, 255, nothing)

while True:
    #frame = cv2.imread('smarties.png')
  if cap.isOpened():
      rval, frame = cap.read()
    

  while rval:
    rval,frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    hsv = cv2.GaussianBlur(hsv, (21, 21), 0)

    if ReferenceFrame is None:
        ReferenceFrame = hsv
        continue
    
    #Background subtraction and image binarization
    FrameDelta = cv2.absdiff(ReferenceFrame, hsv)
    FrameThresh = cv2.threshold(FrameDelta, 25, 255, cv2.THRESH_BINARY)[1]

    #Dilate image and find all the contours
    FrameThresh = cv2.dilate(FrameThresh, None, iterations=2)
    cnts, _ = cv2.findContours(FrameThresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

    QttyOfContours = 0
    
    #plot reference lines (entrance and exit lines) 
    cv2.line(frame, (0,170), (2000,170), (255, 0, 0), 5)

    cv2.line(frame, (0,470), (2000,470), (0, 0, 255), 5)

    #check all found countours
    for c in cnts:
        #if a contour has small area, it'll be ignored
        if cv2.contourArea(c) < MinCountourArea:
            continue

        QttyOfContours = QttyOfContours+1    

        #draw an rectangle "around" the object
        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)


        #find object's centroid
        CoordXCentroid = int(x+x+w)/2
        CoordYCentroid = int(y+y+h)/2
        ObjectCentroid = (x,y)
        cv2.circle(frame, ObjectCentroid, 2, (0, 255, 0), 5)

        if (CheckEntranceLineCrossing(CoordYCentroid,170,470)):
            EntranceCounter += 1

        if (CheckExitLineCrossing(CoordYCentroid,170,470)):  
            ExitCounter += 1

        print ("Total countours found: "+str(QttyOfContours))


        
        #Write entrance and exit counter values on frame and shows it
    cv2.putText(frame, "Entrances: {}".format(str(EntranceCounter)), (10, 50),
    cv2.FONT_HERSHEY_SIMPLEX, 2, (250, 0, 1), 2)
    cv2.putText(frame, "Exits: {}".format(str(ExitCounter)), (10, 110),
    cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2)



    imS = cv2.resize(frame, (400, 400))                    # Resize image
    #imSS = cv2.resize(mask, (200, 200)) 
    #imSSS = cv2.resize(frame, (200, 200))   
    cv2.imshow("frame", imS)
    #cv2.imshow("mask", imSS)
    #cv2.imshow("res", imSSS)

    key = cv2.waitKey(1)
    if key == 27:
       break

cap.release()
cv2.destroyAllWindows()

关于python - 使用带有Python和OpenCV的Raspberry Pi和Android IP摄像机进行对象检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64289417/

相关文章:

c++ - 使用 Python 或其他嵌入式脚本语言部署应用程序

python - 使用 Python 中的其他值更新 numpy 数组中的值

c++ - 使用 OpenCV 描述符匹配 findFundamentalMat

linux - 使用 crontab 运行 python 脚本@reboot

php - 需要什么以及如何将 TTL 指纹模块连接到 Raspberry pi 3

python - Pandas 将索引复制到数据帧

python - 如何根据特定条件对列表中的元素进行计数

python-3.x - 如何在Azure中管理python路径?

opencv - 使用 OpenCV 检测完整的圆

uwp - Windows 10 IoT Core Startup App Headed vs Headless