Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Used below lines of code for contour detection and its corresponding area calculation during printing the area all values are printed but while saving only last value got saved in CSV file

for cnt in contours:

    M= cv2.moments(cnt)
        #print(M)

    if M["m00"] != 0:

        cx = int(M["m10"] / M["m00"])
        cy = int(M["m01"] / M["m00"])
    else:
        cx, cy = 0,0

    center = (cx,cy)


    area = cv2.contourArea(cnt)
    #V1 = np.asarray(area)
    print(area)

    df = pd.DataFrame()
    df['Area'] = area

    df.to_csv("C:pfmdataframe_csvL501.csv")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
268 views
Welcome To Ask or Share your Answers For Others

1 Answer

In every iteration of the loop, you create a new, empty DataFrame, put one thing into it, and write it out to a file. Each time, it writes over the previous output and what is left at the end is the last one. This happens because the file is opened in write mode by default.

(If "write mode" means nothing to you, you should review Python file open modes in your favorite language reference.)

Fortunately, the to_csv function has a mode parameter that you can set to 'a' to open the file for appending. If you do that, each write should append to the end of the file.

Alternately, you could accumulate all the output in one big DataFrame and write the whole thing out once after the loop terminates. This would probably be faster, but would require more memory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...