KV file read-write in Python & C + +

Source: Internet
Author: User
Tags unpack

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 + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.