将图片放入到白色或黑色背景图中,前提是图片小于背景图片的尺寸,原图为如下,长为192,宽为64。

python 白底黑字 python背景变黑代码_python 白底黑字

1.将图片放入到白色背景图(224,224)中

import cv2
import numpy as np
def img_resize_to_target_white(image):
target = np.ones((224,224),dtype=np.uint8)*255
ret = cv2.cvtColor(target, cv2.COLOR_GRAY2BGR)
h = image.shape[0]
w = image.shape[1]
for i in range(224):
for j in range(224):
if(i < h) and (j < w):
ret[i, j, 0] = image[i, j, 0]
ret[i, j, 1] = image[i, j, 1]
ret[i, j, 2] = image[i, j, 2]
else:
ret[i, j, 0] = 255
ret[i, j, 1] = 255
ret[i, j, 2] = 255
return ret
if __name__ == '__main__':
image = cv2.imread('/home/yasin/桌面/test.png')
 img_new_white = img_resize_to_target_white(image)
 cv2.imshow("img_new_white", img_new_white)
cv2.waitKey()

运行结果为:

python 白底黑字 python背景变黑代码_python 白底黑字_02

2.将图片放入到黑色背景图(224,224)中

import cv2
def img_resize_to_target_black(image):
target = np.zeros((224,224),dtype=np.uint8)
 bgr_img = cv2.cvtColor(target, cv2.COLOR_GRAY2BGR)
h = image.shape[0]
w = image.shape[1]
for i in range(h):
for j in range(w):
 bgr_img[i, j, 0] = image[i, j, 0]
 bgr_img[i, j, 1] = image[i, j, 1]
 bgr_img[i, j, 2] = image[i, j, 2]
 return bgr_img
if __name__ == '__main__':
image = cv2.imread('/home/yasin/桌面/test.png')
 img_new_black = img_resize_to_target_black(image)
 cv2.imshow("img_new_black", img_new_black)
cv2.waitKey()

运行结果为:

python 白底黑字 python背景变黑代码_背景图_03

以上这篇python 实现将小图片放到另一个较大的白色或黑色背景图片中就是小编分享给大家的全部内容了,希望能给大家一个参考。