首页 > 解决方案 > Python如何在for循环中使用if进行特定输出

问题描述

我正在尝试编写一个...for循环来隔离与值变化相对应的系列中的元素:

Input example: 1 1 1 2 2 2 2 3 3 1 1 2 2 2
Desired output: 1 2 3 1 2 <--- stores only the values that change from the previous value

编辑:我想这样做的原因是计算视频中的车辆。我在这段代码中使用的算法是背景减法和连通分量标记。将视频裁剪为特定大小我正在尝试添加计算通过帧的“blob”的代码。

编码:

from __future__ import print_function
import cv2 as cv


backSub = cv.createBackgroundSubtractorMOG2()
backSub.setVarThreshold(150)
capture = cv.VideoCapture('vtest.avi')

total_vehicle = 0 
while True:
    ret, frame = capture.read()
    crop = frame[300:, 260:360]
    if frame is None:
        break
    
    fgMask = backSub.apply(crop)
    


    #erode-dilate
    erode_img = cv.erode(fgMask, cv.getStructuringElement(cv.MORPH_ELLIPSE, (5,3)),iterations=2)
    dilate_img = cv.dilate(erode_img,cv.getStructuringElement(cv.MORPH_ELLIPSE, (10,3)),iterations=6)

    #contour
    con = cv.findContours(dilate_img, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)[-2]

    color = cv.cvtColor(dilate_img, cv.COLOR_GRAY2BGR)
    image = cv.drawContours(crop, con, -1, (0,255,0),2)

    output = cv.connectedComponentsWithStats(dilate_img, 8, cv.CV_32S)
    (nolabel, label, stats, centroid) = output

    blob = 0
    for i in range(0, nolabel):
        if stats[i,cv.CC_STAT_AREA]>10:
            blob += 1
            #want to edit this statement
            if blob > 1:
                total_vehicle += 1
                
    print(total_vehicle)
    
    cv.imshow('Frame', frame)
    cv.imshow('dilate', dilate_img)



    
    keyboard = cv.waitKey(30)
    if keyboard == 'q' or keyboard == 27:
        break

total_vehicle正在跟踪 blob 的总数,但不只过滤那些与前一个不同的值。

标签: pythonpython-3.xopencv

解决方案


假设您有一个带有数字的列表:

numbers = [1, 1, 1, 2, 2, 2, 2, 3, 3, 1, 1, 2, 2, 2]

您可以简单地遍历数字并使用预先分配的注释变量检查它们的值,该变量存储最后打印的数字。

note = None # Assign variable with no value
for number in numbers:
    if number != note:
        note = number
        print(number, end=" ")

其输出将是:

>>> 1 2 3 1 2

注意:我已经使用print(number, end=" ")了为了在一行中打印输出,就像在您给定的示例中一样。


推荐阅读