如何从 Python 中的 for-in 循环加载数据?

问题描述 投票:0回答:1

我正在尝试将 detector.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)

这个 for 级联 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

有人可以帮助我吗?

python opencv image-processing computer-vision
1个回答
0
投票

我认为您的代码存在的问题是缩进。在代码中-

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)

让我知道这是否有效

© www.soinside.com 2019 - 2024. All rights reserved.