简体   繁体   English

从opencv将实时数据保存到python中的txt文件中

[英]Saving real time data into txt file in python from opencv

I'm making a project with python and opencv to measure distance between two points and then transfer those values to another PC in real time. 我正在使用python和opencv创建一个项目,以测量两个点之间的距离,然后将这些值实时传输到另一台PC。

I need to export real time data that I get from the code in a text file, but currently I can't make it, I can create the file but this is empty. 我需要将从代码中获取的实时数据导出到文本文件中,但目前无法实现,我可以创建该文件,但此文件为空。 I need that the data shows in a column like this picture. 我需要将数据显示在这样的列中。

测试

The code is this: 代码是这样的:

import cv2   
import numpy as np
#Captura de video a traves de la webcam
cap=cv2.VideoCapture(0)
D = []
max_samples = 10000 

while(1):
    with open('new.txt', 'w') as outfile:
        d=0.1
        centers=[]
        _, img = cap.read()

        hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV) #Se obtiene un histograma basada en las saturaciones de colores.

        blue_lower=np.array([95,150,100],np.uint8)
        blue_upper=np.array([150,255,255],np.uint8)

        blue=cv2.inRange(hsv,blue_lower,blue_upper) #Se crea una mascara utilizando intervalos de color azul.

        kernel = np.ones((5 ,5), "uint8") #Crea una matriz de 5x5 la cual recorrera el video,
        blue = cv2.morphologyEx(blue,cv2.MORPH_OPEN,kernel)
        blue = cv2.morphologyEx(blue,cv2.MORPH_CLOSE,kernel)    

        blue=cv2.erode(blue,kernel, iterations=1) #Se erosiona utilizando el kernel sobre la mascara.
        res1=cv2.bitwise_and(img, img, mask = blue) #La nueva imagen reemplazara a blue.


        (_,contours,hierarchy)=cv2.findContours(blue,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #Encuentra los contornos de los objetos que se ven en el filtro

        for pic, contour in enumerate(contours):
            area = cv2.contourArea(contour) #funcion de opencv que obtiene los contornos
            mayor_contorno = max(contours, key = cv2.contourArea)

            if(area>1000):
                x,y,w,h = cv2.boundingRect(contour) #Encuentra coordenadas de los contornos.
                img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
                cv2.putText(img,"Marcador",(x,y),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,0,0))
                M = cv2.moments(contour) #Se obtiene el centro de masa de los marcadores enconrados.
                cx = int(M['m10'] /M['m00'])
                cy = int(M['m01'] /M['m00'])
                centers.append([cx,cy])
                cv2.circle(img, (cx, cy), 7, (255, 255, 255), -1)

            if len(centers)==2:
                D = (np.linalg.norm(cx-cy))/10 #Se aplica distancia euclidiana para encontrar la distancia entre los centros de masa.
                print(D)
                outfile.write(" %d \n")

        cv2.imshow("Color Tracking",img)
        if cv2.waitKey(10) & 0xFF == ord('q'):
            outfile.close()
            print('The data is now the the new.txt file')
            cap.release()
            cv2.destroyAllWindows()
            break

The problem is caused by the use of with in an inadequate way, when you create a variable with it it is destroyed when leaving that context, in your case you create outfile, and at the end of that iteration you are eliminating (internally it is closing) , and in the other iteration you are creating another outfile and you are deleting them. 问题是由于使用with的方式不足而引起的,当使用它创建变量时,在离开该上下文时销毁了它,在这种情况下,您创建了outfile,并且在迭代结束时要消除(内部是关闭),然后在另一个迭代中创建另一个输出文件,然后将其删除。

In your case, I recommend opening the file before the loop: 根据您的情况,我建议在循环之前打开文件:

outfile = open('new.txt', 'w')

while True:
    d=0.1
    centers=[]
    _, img = cap.read()
    [...]

I have worked on opencv a bit. 我已经在opencv上工作了一点。 Maybe this link might help 也许此链接可能有帮助

 outfile.write(" %d \n" %D)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM