python 中位数填充_python – 如何用图像的中值有效地填充RGB numpy数组?

您可以通过以下方式轻松完成:

import numpy as np

a = np.asarray([[1,2,3,4,5,6],

[8,4,5,6,7,7],

[1,2,3,4,5,6],

[1,2,3,4,5,6],

[1,2,3,4,5,6],

[1,2,3,4,5,6]])

b = a * 3

c = a * 4

d = (a,b,c)

im = np.asarray([np.pad(x, (2,), 'constant', constant_values=(np.median(x) ,)) for x in d])

print im

输出:

[[[ 4 4 4 4 4 4 4 4 4 4]

[ 4 4 4 4 4 4 4 4 4 4]

[ 4 4 1 2 3 4 5 6 4 4]

[ 4 4 8 4 5 6 7 7 4 4]

[ 4 4 1 2 3 4 5 6 4 4]

[ 4 4 1 2 3 4 5 6 4 4]

[ 4 4 1 2 3 4 5 6 4 4]

[ 4 4 1 2 3 4 5 6 4 4]

[ 4 4 4 4 4 4 4 4 4 4]

[ 4 4 4 4 4 4 4 4 4 4]]

[[12 12 12 12 12 12 12 12 12 12]

[12 12 12 12 12 12 12 12 12 12]

[12 12 3 6 9 12 15 18 12 12]

[12 12 24 12 15 18 21 21 12 12]

[12 12 3 6 9 12 15 18 12 12]

[12 12 3 6 9 12 15 18 12 12]

[12 12 3 6 9 12 15 18 12 12]

[12 12 3 6 9 12 15 18 12 12]

[12 12 12 12 12 12 12 12 12 12]

[12 12 12 12 12 12 12 12 12 12]]

[[16 16 16 16 16 16 16 16 16 16]

[16 16 16 16 16 16 16 16 16 16]

[16 16 4 8 12 16 20 24 16 16]

[16 16 32 16 20 24 28 28 16 16]

[16 16 4 8 12 16 20 24 16 16]

[16 16 4 8 12 16 20 24 16 16]

[16 16 4 8 12 16 20 24 16 16]

[16 16 4 8 12 16 20 24 16 16]

[16 16 16 16 16 16 16 16 16 16]

[16 16 16 16 16 16 16 16 16 16]]]

或者在你的特殊情况下:

import numpy as np

from PIL import Image

filePath = '/home/george/Desktop/img.jpg'

Img = Image.open(filePath)

img = np.asarray(Img, np.int)

shp = np.shape(img)

img = img.transpose(2,0,1).reshape(3,215,215)

leftPad = round(float((255 - shp[0])) / 2)

rightPad = round(float(255 - shp[0]) - leftPad)

topPad = round(float((255 - shp[1])) / 2)

bottomPad = round(float(255 - shp[1]) - topPad)

pads = ((leftPad,rightPad),(topPad,bottomPad))

img_arr = np.ndarray((3,255,255),np.int)

for i,x in enumerate(img):

cons = np.int(np.median(x))

x_p = np.pad(x,pads,

'constant',

constant_values=cons)

img_arr[i,:,:] = x_p

im_shp = np.shape(img_arr)

ii = np.uint8(img_arr).transpose(1,2,0)

im = Image.fromarray(np.array( (ii) ))

im.show()

im.save((filePath), "JPEG")

输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值