askrav askrav - 1 month ago 6
Python Question

OpenCV: Save frame matrix to text file (Python)

I have got a USB connected webcam and want to save captured frame to text file. Frame is numpy array and i need to get only red color values. So, here's my code:

vc = cv2.VideoCapture(1)

if vc.isOpened():
rval, frame = vc.read()
frame = imutils.resize(frame, width=640, height=480)
print(frame[...,...,2])
savetxt('../test.txt', frame[...,...,2])


print gets me this:

[[127 125 125 ..., 114 118 101]

[123 126 125 ..., 111 112 100]

[129 124 122 ..., 116 116 100]

...,

[121 120 121 ..., 97 104 88]

[118 121 121 ..., 96 103 90]

[116 122 120 ..., 97 105 90]]

But even if I could print the whole array, it does not fit terminal window.
So i'd like to save it to file but savetxt func is not working as I want. Here's the beginning of test.txt:
1.270000000000000000e+02 1.250000000000000000e+02 1.250000000000000000e+02

and so on.

I'm using OpenCv 3.1 and Python 2.7.12

Any help?

Answer

savetxt default format is '%.18e' which explains the format you're getting.

numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ')[source]ΒΆ

Change the format specifier with fmt parameter to print integers instead of floats:

savetxt('../test.txt', frame[...,...,2],fmt="%d")
Comments