【问题标题】:Python how to make specific output using if in for loopPython如何在for循环中使用if进行特定输出
【发布时间】:2021-10-15 06:00:15
【问题描述】:

我正在尝试编写一个...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 的总数,但不只过滤那些与前一个不同的值。

【问题讨论】:

  • 你必须先试一试。您只需要记住最后一个数字是什么,并在数字发生变化时打印(并记住)。
  • 输入是什么?分享你的实际代码
  • 欢迎来到 Stack Overflow。我们只能告诉您您实际向我们展示的代码有什么问题。请阅读How to Askmeta.stackoverflow.com/questions/334822/…。但是,您所问的问题几乎没有意义,而且您似乎对正确描述问题的了解还不够,更不用说解决它了。在这种情况下,Stack Overflow 无法为您提供帮助。您应该尝试遵循教程,与您的讲师交谈,或者作为最后的手段,使用 Reddit 或 Quora 等论坛。
  • 我不明白您的变量如何减少?你唯一的增量 total_vehicle
  • 减少是在 blob 中。如果视频中的 blob > 1,则总车辆增加。但是,如果它保持在 >1,如 2 2 2 2,则总车辆保持递增。我只想要基于其变化的总车辆增量。

标签: python python-3.x opencv


【解决方案1】:

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

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=" ") 以便在一行中打印输出,就像在您给定的示例中一样。

【讨论】:

    猜你喜欢
    • 2016-05-15
    • 2013-09-28
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    相关资源
    最近更新 更多