Home > Mobile >  How to print one element in a list at a time and not carry forward the previous one?
How to print one element in a list at a time and not carry forward the previous one?

Time:06-28

enter image description here

As you can see in the image, I'm trying to achieve the expected behavior but somehow cannot make it. I believe the error is come from for loop that I coded.

I tried with break, but it's not what I want since it break out the loop once it draws the first contour.

For you info, the contour is in 3D list.

First contour: [[[125 300]] [[124 301]] [[124 302]] [[124 303]] [[124 304]] [[125 304]] [[126 304]] [[127 304]] [[128 304]] [[129 304]] [[130 304]] [[131 304]] [[132 304]] [[133 304]] [[132 303]] [[131 302]] [[130 301]] [[129 301]] [[128 300]] [[127 300]] [[126 300]]]

Does it relate to python queue ?

Anyone has idea on this ?

import cv2
import math
from matplotlib import pyplot as plt


def lines():

    # reading image in BGR format
    img = cv2.imread("C://Users/ranz/Desktop/1.bmp")
    res = cv2.resize(img, (570,610), cv2.INTER_LINEAR)

    cnt_point = []

    #grayscale
    gry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    #threshold for black pixel
    _, thresh = cv2.threshold(gry,0,255,cv2.THRESH_BINARY_INV)
    
    #find all contours
    cnt,_ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    
    #draw blank mask 
    blank_mask = np.zeros((thresh.shape[0], thresh.shape[2], 3), np.uint8)

    for i in range(len(cnt)):
        cv2.drawContours(blank_mask, cnt[i], -1, (0, 255, 0), 1)
        print(cnt[i])
        cv2.imshow('test',blank_mask)
        cv2.waitKey(0)
        
cv2.destroyAllWindows()
lines()

CodePudding user response:

Create a new blank_mask each time through the loop, rather than drawing on the same mask as the previous iteration.

    for i in range(len(cnt)):
        blank_mask = np.zeros((thresh.shape[0], thresh.shape[2], 3), np.uint8)
        cv2.drawContours(blank_mask, cnt[i], -1, (0, 255, 0), 1)
        print(cnt[i])
        cv2.imshow('test',blank_mask)
        cv2.waitKey(0)
  • Related