python - 如何在python的for循环中加载数据?
问题描述
你好 o 尝试将 detect.multiscale 代码与 calc.hist 代码结合起来。我尝试运行这个程序,但我无法在 for in 循环中访问“w”。??
import cv2
import numpy as np
from matplotlib import pyplot as plt
import time
import sys
import serial
#execfile("/home/arizal/Documents/Sorting Jeruk/motor1.py")
#ser = serial.Serial('/dev/ttyACM0', 9600)
#Cascade jeruk
jeruk_cascade = cv2.CascadeClassifier('cascade.xml')
camera = cv2.VideoCapture(1)
base1 = cv2.imread('base11.jpg')
base2 = cv2.imread('base22.jpg')
base3 = cv2.imread('base33.jpg')
#Set hist parameters
hist_height = 64
hist_width = 256
nbins = 32
bin_width = hist_width/nbins
hrange = [0,180]
srange = [0,256]
ranges = hrange+srange # ranges = [0,180,0,256]
#Create an empty image for the histogram
e = np.zeros((hist_height,hist_width))
#print ("h : ",h)
#print type(h)
#x=1
这是为了检测。多尺度循环
while 1:
grabbed, img = camera.read()
cam = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if not grabbed:
"Camera could not be started."
break
# add this
# image, reject levels level weights.
jeruks = jeruk_cascade.detectMultiScale(cam, 1.03, 5)
this for cascade for in 循环,用于在对象上给出矩形标记
# add this
for (x,y,w,h) in jeruks:
cv2.rectangle(img,(x,y),(x+w,y+h),(17,126,234),2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'Jeruk',(x+w,y+h), font, 1, (17,126,234), 2, cv2.LINE_AA) #---write the text
roi_gray = cam[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
并在检测到对象时计算直方图
if w > 250 :
print ('w', w)
histcam = cv2.calcHist([cam], [0], None, [nbins], [0,256])
cv2.normalize(histcam,histcam, hist_height, cv2.NORM_MINMAX)
hist=np.int32(np.around(histcam))
但我收到了这个错误:
Traceback (most recent call last):
File "/home/arizal/Documents/Sorting Jeruk/doalcoba.py", line 65, in <module>
if w > 250 :
NameError: name 'w' is not defined
任何人都可以帮助我吗?
解决方案
我认为您的代码存在缩进的问题。在代码中 -
for (x,y,w,h) in jeruks:
....
和
if w > 250 :
....
处于同一级别的缩进。(x,y,w,h)
仅适用于for
循环,而不是循环之外。修复你的缩进 -
for (x,y,w,h) in jeruks:
....
if w > 250 :
print ('w', w)
让我知道这是否有效
推荐阅读
- java - 为什么我在尝试注册帐户时会收到错误消息?
- mongodb - 如何使用 `mongorestore` 使用 TAR.GZ 文件恢复数据库
- typescript - 如何扩展现有 npm 模块的类型定义?
- python - 对于以下模式,PySpark regexp_replace 无法按预期工作
- c - 连续获得 k 个相等值的有效方法
- vue.js - 验证 v-file-input 验证
- python - 二叉搜索树搜索方法
- javascript - 如何在 Javascript 中对特定的 DOM 节点进行排序?
- c++ - 为什么我可以使用比分配更多的内存?
- c# - Windows Server 2016:作为 LSA 登录的 Windows 服务器无法选择 Microsoft David Voice