cv2.imdecode () function reads from a specified memory cache data and converts the data (decoded) into an image format; mainly for recovering the image data transmitted from the network.
cv2.imencode () function is to convert the image format (encoded) into a data stream, assigned to the memory cache; mainly for compressing image data format, to facilitate network transmission.
imdecode () use
Reading image data from the network and converted into a picture format:
# -*- coding: utf-8 -*- import numpy as np import urllib import cv2 url = 'https://www.baidu.com/img/bd_logo1.png?where=super' resp = urllib.urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) cv2.imshow('URL2Image',image) cv2.waitKey()
display image:
imencode () use
The picture coding into the cache, and saves it to:
# - * - Coding: UTF- . 8 - * - Import numpy AS NP Import the urllib Import CV2 img = cv2.imread ( ' 0122.jpg ' ) # ' .jpg ' represents the current image img jpg format according encoded in different formats the result of encoding is not the same img_encode = cv2.imencode ( ' .jpg ' , IMG) [ . 1 ] # imgg = cv2.imencode ( ' .png ' , IMG) data_encode = np.array (img_encode) str_encode = data_encode.tostring () # save cache data locally Open ( 'img_encode.txt', 'WB') AS f: f.write(str_encode) f.flush()
imencode () + imdecode () use
Save the picture to your local coding, decoding read local files restored to image formats:
# - * - Coding: UTF- . 8 - * - Import numpy AS NP Import the urllib Import CV2 img = cv2.imread ( ' 0122.jpg ' ) # ' .jpg ' represents the current image img jpg format according encoded in different formats the result of encoding is not the same img_encode = cv2.imencode ( ' .jpg ' , IMG) [ . 1 ] # imgg = cv2.imencode ( ' .png ' , IMG) data_encode = np.array (img_encode) str_encode = data_encode.tostring () # save cache data locally, saved in txt format with open ('img_encode.txt', 'wb') as f: f.write(str_encode) f.flush() with open('img_encode.txt', 'rb') as f: str_encode = f.read() nparr = np.fromstring(str_encode, np.uint8) img_decode = cv2.imdecode(nparr, cv2.IMREAD_COLOR) cv2.imshow("img_decode", img_decode) cv2.waitKey()
or
# - * - Coding: UTF- . 8 - * - Import numpy AS NP Import the urllib Import CV2 img = cv2.imread ( ' 0122.jpg ' ) # ' .jpg ' represents the current image img jpg format according encoded in different formats the result of encoding is not the same img_encode = cv2.imencode ( ' .jpg ' , IMG) [ . 1 ] # imgg = cv2.imencode ( ' .png ' , IMG) data_encode = np.array (img_encode) str_encode = data_encode.tostring () # save cache data locally, saved in txt format with open ('img_encode.txt', 'wb') as f: f.write(str_encode) f.flush() with open('img_encode.txt', 'rb') as f: str_encode = f.read() image = np.asarray(bytearray(str_encode), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) cv2.imshow('img_decode',image)