kv文件讀寫 in Python & C++

文件格式均爲kv對,即keylength, key, valuelen, value. 如何對其進行讀寫操作,本文列出demo code。感謝濤哥貢獻部分代碼,這裏分享,方便大家使用。


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);
	if (!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();
	unsigned 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();
}


如果value是一張圖片的data,調用的時候可以用opencv的imdecode直接進行轉換,生成cv::Mat類型的圖片

cv::Mat buf(1,value.size(),CV_8U,(void *)value.c_str());
cv::Mat srcmat = cv::imdecode(buf,1);






發佈了475 篇原創文章 · 獲贊 670 · 訪問量 1000萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章