python - 如何让我的 OpenCV 代码正常工作而不会卡住
问题描述
我是一名新的编码员,我使用 OpenCV 库 [Python 代码] 从事毕业项目。
我需要编写代码来检测恒定背景中的气球并对其进行监控。
我决定使用 Substruct 函数 + HoughCircles,问题是每个代码都运行良好[除了圆形检测,它工作得不是最好的],当我结合这两个代码时,它工作得非常慢并且卡住了很多,有人可以建议我吗如何正确插入它以使其不会卡住并以某种方式改善 HoughCircles?
import numpy as np
#import RPi.GPIO as GPIO
import time
import cv2
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
while True:
ret, frame = cap.read()
if frame is None:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
fgmask = fgbg.apply(gray)
#changes = sum(sum(fgmask>200))
changes = (fgmask>200).sum() #
is_moving = (changes > 10000)
print(changes, is_moving)
items = []
contours, hier = cv2.findContours(fgmask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
area = cv2.contourArea(cnt)
if 200 < area:
(x,y,w,h) = cv2.boundingRect(cnt)
cv2.rectangle(fgmask, (x,y),(x+w,y+h),255, 2)
cv2.rectangle(frame, (x,y),(x+w,y+h),(0,255,0), 2)
items.append( (area, x, y, w, h) )
if items:
main_item = max(items)
area, x, y, w, h = main_item
if w > h:
r = w//2
else:
r = h//2
cv2.circle(frame, (x+w//2, y+h//2), r, (0,0,255), 2)
print(x + w // 2, y + h // 2)
circles = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,50,
param1=50,param2=30,minRadius=0,maxRadius=0)
#circles = np.uint16(np.around(circles))
if circles is not None:
# convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles[0, :]).astype("int")
# loop over the (x, y) coordinates and radius of the circles
for (x, y, r) in circles:
# draw the circle in the output image, then draw a rectangle in the image
# corresponding to the center of the circle
cv2.circle(gray, (x, y), r, (0, 255, 0), 4)
#cv2.rectangle(gray, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
# time.sleep(0.5)
print("Column Number: ")
print(x)
print("Row Number: ")
print(y)
print("Radius is: ")
print(r)
cv2.imshow('fgmask', fgmask)
cv2.imshow('frame', frame)
cv2.imshow('gray',gray)
k = cv2.waitKey(10) & 0xff
if k == 27:
break
cv2.destroyAllWindows()
cap.release()
非常感谢!
解决方案
推荐阅读
- machine-learning - 是否有关于检测乐器是否演奏正确音符的论文或模型?
- ios - 播放 Apple Music Song 时出现问题,playbackStoreID
- javascript - 是什么导致我对 IndexOf 数组的单元测试出现此 AssertionError 失败
- typescript - Typescript - 如何只从一个文件夹编译
- html - 如何制作一个填充 100% 主要内容的水平条?
- python - Python 从导入根包中引用子模块
- ag-grid - ag-grid nativescript-vue 组件未注册
- php - 如果超过两年,请检查帖子的发布日期
- emacs - 如何注册递归“加载路径”?
- python - Python 如何将列表的值与文件进行比较,然后将值保存到新文件中?