首页 > 解决方案 > 如何在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

任何人都可以帮助我吗?

标签: pythonopencvimage-processingvision

解决方案


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

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)

让我知道这是否有效


推荐阅读