File formats are kv pairs, i.e. keylength, key, Valuelen, value. How to read and write it, this article lists the demo code. Thank you for your part of the code, here to share, easy to use.
Python:
Def readimg (): FR = open (' img_2963.jpg ', ' r ') Keylen = Struct.unpack (' i ', Fr.read (4)) [0]key = Fr.read (keylen) Valuelen = Struct.unpack (' I ', Fr.read (4)) [0]value = Fr.read (Valuelen) fr.close () def writeimg (): FW = open (' Img_to_write ', ' w ') key = ' Key ' Fw.write (Struct.pack (' I ', Len (key))) Fw.write (key) Fw.write (struct.pack (' I ', Len (val))) Fw.write (Val) Fw.close ()
C++:
inline bool Readkv (IStream &ifs,string &key,string &value) {int Keylen;ifs.read ((char*) &keylen,4); !IFS) {return false;} Key.resize (Keylen); Ifs.read ((char*) key.c_str (), keylen); int Valuelen;ifs.read ((char*) &valuelen,4); Value.resize (Valuelen); Ifs.read ((char*) value.c_str (), Valuelen); return true;} inline void writekv (ostream &ofs,const string & key,const String & value) {unsigned int klen = Key.size (); Unsig Ned int vlen = Value.size (), Ofs.write ((const char*) &klen,4), Ofs.write (Key.c_str (), Klen), Ofs.write ((const char*) &vlen,4); Ofs.write (Value.c_str (), Vlen); Ofs.flush ();}
If value is the data of a picture, the call can be converted directly with OpenCV Imdecode, creating a cv::mat type of picture
Cv::mat buf (1,value.size (), cv_8u, (void *) value.c_str ()); Cv::mat Srcmat = Cv::imdecode (buf,1);
KV file read-write in Python & C + +