OpenCV C++中的Mat格式灰度图转Python中的Image
import numpy as np
#height、width为图片高、宽
#mat_data为二进制数据
#dtype与原Mat格式对应
#转为灰度图
image = np.frombuffer(mat_data, dtype=np.int16).reshape(height, width)
灰度图转RGB图
import cv2
import numpy as np
image_rgb = np.zeros(gray_image.shape, dtype = np.uint8)
#灰度图为uint16, 转成uint8的图片
for index in range(len(gray_image)):
image_rgb[index] = gray_image[index] >> 2
image_rgb = cv2.cvtColor(image_rgb, cv2.COLOR_GRAY2BGR)
RGBA图片Byte数据转Python中的RGBA图
import numpy as np
image = np.frombuffer(image_file, dtype=np.uint8).reshape(image_height, image_width, 4)
RGBA图转RGB图
import cv2
image_rgb = cv2.cvtColor(image_rgba, cv2.COLOR_RGBA2BGR)
将图片复制到另一个图片指定位置
import cv2
import numpy as np
base_image = np.zeros((base_height, base_width, 3), np.uint8) #创建空白RGB图片
src_image = cv2.imread('./test.jpg') #从文件读入图片
image_height = src_image.shape[0] #获取图片的长宽
image_width = src_image.shape[0]
base_image [10 : image_height + 10, 20: image_width + 20] = src_image #将图片src_image复制到base_image的(10, 20),注意base_image 必须足够大,可以装的下src_image