python - txt 文件不会在 windows 中用 python 编写,它适用于 mac
问题描述
我编写了一段代码,它拍摄视频并识别人脸并计算人与相机(即机器人的眼睛)的距离。我需要 txt 格式的数据,所以我将其写入 distance_data.txt 但我的文件始终为空。我已经在 Mac 计算机上运行了代码,它运行得非常好,文件不为空。
import cv2
import time
import numpy as np
person_cascade = cv2.CascadeClassifier('human_recognition.txt')
cap = cv2.VideoCapture('oct23_2.avi')
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('oct23_2out.avi',fourcc, 20.0, (640,360))
distance_data = open('distance_data.txt','w')
timer=-1
while (cap.isOpened()):
r, frame = cap.read()
if r:
frame = cv2.resize(frame,(640,360)) # Downscale to improve frame rate
gray_frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) # Haar-cascade classifier needs a grayscale image
cv2.imshow('gray',gray_frame)
#print(gray_frame.type())
rects = person_cascade.detectMultiScale(gray_frame)
max=0
#print(rects)
(x, y, w, h) = rects[0]
cv2.rectangle(frame, (x,y), (x+w ,y+h),(0,255,0),2)
#fshape = frame.shape
#fheight = fshape[0]
#fwidth = fshape[1]
timer=timer+1
xpos=(0.03421)*(w*w)-8.1183*w+521.841
yn=360-y
heightinvid=0.0197377*yn-0.0194
realhieght=((-0.4901)*(heightinvid* heightinvid)+4.4269*heightinvid+8.30356)/ 0.927183854
horizontalp=x+w/2
#print(timer+1 , ",", xpos, )
#if (xpos<=41 and xpos>=40):
#print("height of the human is ", realhieght+149, "or", (-0.000184)*yn*yn+0.08506*yn+8.43461+149)
cm_deviation_in_x=-0.02033898*(320-horizontalp)
#print("Horizontal position of human is ", cm_deviation_in_x, " cm.")
newxpos = format (xpos, '.3f')
distance_data.write("Hi")
distance_data.write(str(newxpos))
distance_data.write(',')
distance_data.write(str(format(cm_deviation_in_x, '.3f')))
distance_data.write("\r\n")
#print(w)
#print("x position of the human is = ",xpos)
#fourcc = cv2.VideoWriter_fourcc(*'XVID')
#out = cv2.VideoWriter('output25.avi',fourcc, 20.0, (fwidth,fheight))
cv2.imshow("preview", frame)
out.write(frame)
k = cv2.waitKey(10)
#print(w,h)
if k & 0xFF == ord("q"): # Exit condition
break
distance_data.flush()
cap.release()
cv2.destroyAllWindows()
解决方案
推荐阅读
- facebook-graph-api - Instagram 视频发布时的图形 API 问题 - 媒体上传失败,错误代码为 2207026"
- r - plot_ly:可以为 scatter3D 绘图设置主题吗?
- javascript - 如何在 onSubmit 后使用表单显示内容的时间超过一秒钟
- msp430 - 使用 MSP430FR5969 MCU 从 TMP117 传感器读取温度值
- stored-procedures - 如何将程序的使用权限授予广泛的角色组?
- api - QuickBooks online 如何确定 ExpenseAccountRef.value?我是否需要查询一个 ACCOUNT 对象来确定该值?
- laravel - 在 Laravel 中发送密码重置链接返回空数组
- postgresql - Postgres - 向角色组中的现有用户授予权限
- python - 我当前的代码收到一个输入,该输入说明要加起来多少斐波那契数,但在六个测试运行之一中输出是错误的
- selenium-webdriver - Selenium中Testng框架和黄瓜框架的区别