從網絡讀取圖像數據并展示
-
需要使用
cv2.imdecode()
函數,從指定的內存緩存中讀取數據,并把數據轉換(解碼)成圖像格式;主要用于從網絡傳輸數據中恢復出圖像。
# -*- coding: utf-8 -*-
import
numpy
as
np
from
urllib
import
request
import
cv2
url
=
'https://www.baidu.com/img/superlogo_c4d7df0a003d3db9b65e9ef0fe6da1ec.png?where=super'
resp
=
request
.
urlopen
(
url
)
image
=
np
.
asarray
(
bytearray
(
resp
.
read
(
)
)
,
dtype
=
"uint8"
)
image
=
cv2
.
imdecode
(
image
,
cv2
.
IMREAD_COLOR
)
cv2
.
imshow
(
'url_image_show'
,
image
)
if
cv2
.
waitKey
(
10000
)
&
0xFF
==
ord
(
'q'
)
:
cv2
.
destroyAllWindows
(
)
圖片編碼保存到本地,讀取本地文件解碼恢復成圖片格式并展示
-
需要使用
cv2.imencode()
函數,將圖片格式轉換(編碼)成流數據,賦值到內存緩存;主要用于圖像數據格式的壓縮,方便網絡傳輸。
# -*- coding: utf-8 -*-
import
numpy
as
np
import
cv2
img
=
cv2
.
imread
(
'cat.jpg'
)
'''
cv2.imencode()函數是將圖片格式轉換(編碼)成流數據,賦值到內存緩存中;主要用于圖像數據格式的壓縮,方便網絡傳輸
'.jpg'表示把當前圖片img按照jpg格式編碼,按照不同格式編碼的結果不一樣
'''
img_encode
=
cv2
.
imencode
(
'.jpg'
,
img
)
[
1
]
# imgg = cv2.imencode('.png', img)
data_encode
=
np
.
array
(
img_encode
)
str_encode
=
data_encode
.
tostring
(
)
# 緩存數據保存到本地,以txt格式保存
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
)
'''
# 或
nparr = np.asarray(bytearray(str_encode), dtype="uint8")
img_decode = cv2.imdecode(image, cv2.IMREAD_COLOR)
'''
cv2
.
imshow
(
"img_decode"
,
img_decode
)
if
cv2
.
waitKey
(
10000
)
&
0xFF
==
ord
(
'q'
)
:
cv2
.
destroyAllWindows
(
)
將np圖片(imread后的圖片)轉碼為base64格式
def
image_to_base64
(
image_np
)
:
image
=
cv2
.
imencode
(
'.jpg'
,
image_np
)
[
1
]
image_code
=
str
(
base64
.
b64encode
(
image
)
)
[
2
:
-
1
]
return
image_code
將base64編碼解析成opencv可用圖片
def
base64_to_image
(
base64_code
)
:
# base64解碼
img_data
=
base64
.
b64decode
(
base64_code
)
# 轉換為np數組
img_array
=
np
.
fromstring
(
img_data
,
np
.
uint8
)
# 轉換成opencv可用格式
img
=
cv2
.
imdecode
(
img_array
,
cv2
.
COLOR_RGB2BGR
)
return
img
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
