python-3.x - OpenCV 定位质心在 PiCam 上出现错误
问题描述
我有一个代码可以定位放置在相机前面的物体的质心。我在我的树莓派上运行了代码,我在项目中使用了 PiCam,cv2.moments()
函数的输出对象的所有值都是 0。代码的相关部分是这样的:
import cv2
import numpy as np
from picamera import PiCamera
from picamera.array import PiRGBArray
camera = PiCamera()
camera.resolution = (640,480)
camera.framerate = 16
camera.rotation=180
rawCapture = PiRGBArray(camera, size=(640,480))
for f in camera.capture_continuous(rawCapture,format='bgr',use_video_port=True):
# ret, orig_frame = video.read()
orig_frame = f.array
hsv = cv2.cvtColor(orig_frame, cv2.COLOR_BGR2HSV)
low_red = np.array([100, 100, 100])
up_red = np.array([255, 255, 255])
mask = cv2.inRange(hsv, low_red, up_red)
edges = cv2.Canny(mask, 100, 200)
bit = cv2.bitwise_or(orig_frame, orig_frame, mask= mask)
contours, _ ,heirarchy= cv2.findContours(frame1, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
setpoint = 315
stop1 = 250
stop2 = 370
for c in contours:
M = cv2.moments(c)
print(M) #OUTPUT HAS ALL VALUES 0
# cX = int(M["m10"] / M["m00"])
# cY = int(M["m01"] / M["m00"])
print(M)
语句的输出是:
{'m20': 0.0, 'mu20': 0.0, 'nu30': 0.0, 'm03': 0.0, 'm10': 0.0, 'mu03': 0.0, 'nu02': 0.0, 'm11': 0.0, 'm21': 0.0, 'mu21': 0.0, 'mu02': 0.0, 'mu30': 0.0, 'm12': 0.0, 'm01': 0.0, 'm00': 0.0, 'nu20': 0.0, 'nu03': 0.0, 'nu21': 0.0, 'nu11': 0.0, 'm02': 0.0, 'nu12': 0.0, 'mu11': 0.0, 'mu12': 0.0, 'm30': 0.0}
如您所见,所有值均为 0
但是,如果我在使用其网络摄像头的笔记本电脑上运行相同的代码,则代码运行时不会出错,并且print(M)
语句的输出是具有非零值的对象。
这是我本地机器上的代码:
import cv2
import numpy as np
video = cv2.VideoCapture(0)
def make_custom(x, y):
video.set(3, x)
video.set(4, y)
make_custom(800, 800)
while True:
ret, orig_frame = video.read()
#frame = cv2.GaussianBlur(orig_frame, (5, 5), 0)
hsv = cv2.cvtColor(orig_frame, cv2.COLOR_BGR2HSV)
low_red = np.array([100, 100, 100])
up_red = np.array([255, 255, 255])
mask = cv2.inRange(hsv, low_red, up_red)
frame1 = cv2.GaussianBlur(mask, (5, 5), 1)
edges = cv2.Canny(mask, 100, 200)
bit = cv2.bitwise_or(orig_frame, orig_frame, mask= mask)
contours, _ = cv2.findContours(frame1, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
for c in contours:
# calculate moments for each contour
M = cv2.moments(c)
print(M)
我在两台机器上都使用 Python 3.6
我做错了什么,我该如何纠正?
解决方案
推荐阅读
- azure - 在 Azure Databricks 中反序列化事件中心消息
- git - git 中提交的 sed/grep 标记
- c - gcc 编译器报告警告,但 a.out 工作顺利,否则
- hadoop - Cucumber-Hadoop:如何从 HDFS 位置读取黄瓜特征文件?
- c# - 使用 MIMEKIT 使用数字证书对纯文本文件进行签名和加密
- java - 在 Visual Studio Code 中启动 Java 语言服务器卡在 37%
- javascript - HTML5画布:角度> 2 PI的逆时针弧
- c++ - 基于返回类型的转换和过载扣除
- node.js - 为什么我会丢失帮助程序错误:包含以前工作过的代码的部分
- python - Python函数根据选择的分布绘制随机数