将图片放入到白色或黑色背景图中,前提是图片小于背景图片的尺寸,原图为如下,长为192,宽为64。
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()
运行结果为:
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 实现将小图片放到另一个较大的白色或黑色背景图片中就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。