官方文档详细介绍:
github:https://github.com/opencv/opencv-python
文档:https://docs.opencv.org/4.x/
https://docs.opencv.org/4.x/d8/d6a/group__imgcodecs__flags.html#ga61d9b0126a3e57d9277ac48327799c80
参考
参考
参考
#encoding:utf-8
from cv2 import *
import urllib
import numpy as np
import requests as req
from PIL import Image
from io import BytesIO
from skimage import io
img_src = 'http://n1image.hjfile.cn/shetuan/2017-05-17-1495016837-986-732.jpg'
##############
# opencv #
##############
#opencv不能直接从网络获取图片,但是opencv的VideoCapture类可以从url加载视频
# cap = VideoCapture(img_src)
# if( cap.isOpened() ):
# ret, img = cap.read()
# img = resize(img, (800, 600))
# imshow("image", img)
# waitKey(0)
########################
# opencv+urllib+numpy #
########################
#urllib的urlopen方法返回一个类文件对象,将对象重新编码为图片传给Mat
# resp = urllib.urlopen(img_src)
# image = np.asarray(bytearray(resp.read()), dtype="uint8")
# image = imdecode(image, IMREAD_COLOR)
# image = resize(image, (900, 600))
# imshow("image", image)
# waitKey(0)
########################
# PIL+requests #
########################
#字节形式访问请求响应体,用返回的二进制重新创建一张图片
# response = req.get(img_src)
# image = Image.open(BytesIO(response.content))
# image.show()
########################
# skimage #
########################
#最方便的方法,直接读物网页图片
image = io.imread(img_src)
io.imshow(image)
io.show()
OPENCV Color Space Conversions字段介绍
image指的 PIL的Image类型
1.bytes与base64互转
# bytes转base64
image_base4 = base64.b64encode(image_bytes).decode('utf8')
# base64转bytes
image_bytes = base64.b64decode(image_base64)
2.bytes与Image对象互转
#将bytes结果转化为Image
bytes_stream = io.BytesIO(result)
roiimg = Image.open(bytes_stream)
# 将Image转为bytes
img = Image.open(img_path, mode='r')
imgByteArr = io.BytesIO()
3.bytes与CV2对象互转
# cv2图片对象转为bytes
img = cv2.imread(img_path)
array_bytes = img.tobytes()
# bytes转为cv2图片对象
img_buffer_numpy = np.frombuffer(img_bytes, dtype=np.uint8)
img_numpy = cv2.imdecode(img_buffer_numpy, 1)
4.base64与Image对象互转
# Image转base64
img_buffer = io.BytesIO()
image.save(img_buffer, format='JPEG')
byte_data = img_buffer.getvalue()
base64_str = base64.b64encode(byte_data)
# base64转Image
image = base64.b64decode(base64_str)
image = BytesIO(image)
image = Image.open(image)
5.base64与cv2对象互转
#cv2转base64
base64_str = cv2.imencode('.jpg',image)[1].tostring()
base64_str = base64.b64encode(base64_str)
#base64转cv2
imgString = base64.b64decode(base64_str)
nparr = np.fromstring(imgString,np.uint8)
image = cv2.imdecode(nparr,cv2.IMREAD_COLOR)
6.image与cv2对象互转
# Iamge 转 cv2
img = Image.open("test.jpg")
img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
# cv2 转 Image
img = cv2.imread("test.jpg")
img = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
第一种:PIL读取方式
from PIL import Image
I = Image.open('./0.png')
print(type(I)) #---><class 'PIL.JpegImagePlugin.JpegImageFile'>
print(I.size) #--->(1280, 720)
I.show()
I.save('./save.png')
第二种:imread读取方式
import matplotlib.pyplot as plt
from scipy.misc import imread, imsave
I = imread('./0.png')
print(type(I)) #---><class 'numpy.ndarray'>
print(I.shape) #--->(720, 1280, 3)
print(I.size) #--->2764800
imsave('./save1.png', I)
plt.imshow(I)
plt.show()
第三种:cv2读取方式
import cv2
I = cv2.imread('./0.png')
cv2.namedWindow('input_image', cv2.WINDOW_AUTOSIZE)
I = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY) #灰度化
cv2.imshow('input_image', I)
cv2.imwrite('./save1.png', I)
print(type(I)) #---><class 'numpy.ndarray'>
print(I.shape) #--->(720, 1280, 3)
#参数=0:(也可以是小于0的数值)一直显示,不会有返回值,若在键盘上按下一个键即会消失,则会返回一个按键对应的ascii码值
#参数>0:显示多少毫秒,超过这个指定时间则返回-1
cv2.waitKey(0)
cv2.destroyAllWindows()
第三种:程序处理过程中的图片裁取
tensor格式的图
facecut = im0[int(xyxy[1].item()):int(xyxy[3].item()),
int(xyxy[0].item()):int(xyxy[2].item())]
图片格式的相互转换:
from PIL import Image
import numpy as np
I = Image.open('./0.png')
print(type(I)) #---><class 'PIL.JpegImagePlugin.JpegImageFile'>
print(I.size) #--->(1280, 720)
I_array = np.array(I)
print(type(I_array)) #---><class 'numpy.ndarray'>
print(I_array.shape) #--->(720, 1280, 3)
from PIL import Image
from scipy.misc import imread
I = imread('./0.png')
print(type(I)) #---><class 'numpy.ndarray'>
print(I.shape) #--->(720, 1280, 3)
print(I.size) #--->2764800
I = Image.fromarray(I)
print(type(I)) #---><class 'PIL.Image.Image'>
print(I.size) #--->(1280, 720)
import cv2
from PIL import Image
I = cv2.imread('./0.png')
print(type(I)) #---><class 'numpy.ndarray'>
print(I.shape) #--->(720, 1280, 3)
I = Image.fromarray(I)
print(type(I)) #---><class 'PIL.Image.Image'>
print(I.size) #--->(1280, 720)
总结:
1. 'numpy.ndarray'的形状为(H, W, C),而'PIL.Image.Image'的形状为(W, H)。
2. 'numpy.ndarray'的形状属性为.shape,而'PIL.Image.Image'的形状属性为.size。
Image、cv2、io这三种读取的图片位深度都为16,那么保存的图片的位深度分别为:16、8、8。
imencode()+imdecode()使用
图片编码保存到本地,读取本地文件解码恢复成图片格式:
# -*- coding: utf-8 -*-
import numpy as np
import urllib
import cv2
img = cv2.imread('0122.jpg')
# '.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', 'w') as f:
f.write(str_encode)
f.flush
with open('img_encode.txt', 'r') 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()
或者:
# -*- coding: utf-8 -*-
import numpy as np
import urllib
import cv2
img = cv2.imread('0122.jpg')
# '.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', 'w') as f:
f.write(str_encode)
f.flush
with open('img_encode.txt', 'r') 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)
cv2.waitKey()