【发布时间】:2015-07-26 10:31:41
【问题描述】:
我的 RGB 图像已经过重新缩放,长边变为 256 像素,现在我想用该图像的 RGB 中值填充边框,使生成的图像始终为 256x256 像素。
这段代码已经可以工作了,但我相信还有更简单更优雅的方法来做到这一点:
img = loadAndFitImage(filePath, maxSideLength=256, upscale=True)
shp = img.shape
#the shp in this case is typically (256,123,3) or (99,256,3)
leftPad = (256 - shp[0]) / 2
rightPad = 256 - shp[0] - leftPad
topPad = (256 - shp[1]) / 2
bottomPad = 256 - shp[1] - topPad
# this part looks like there might be a way to do it with one median call instead of 3:
median = (np.median(img[:, :, 0]),np.median(img[:, :, 1]),np.median(img[:, :, 2]))
img = np.lib.pad(img, ((leftPad,rightPad),(topPad,bottomPad),(0,0)),
'constant',constant_values=0)
if leftPad > 0:
img[:leftPad,:,0].fill(median[0])
img[:leftPad,:,1].fill(median[1])
img[:leftPad,:,2].fill(median[2])
if rightPad > 0:
img[-rightPad:,:,0].fill(median[0])
img[-rightPad:,:,1].fill(median[1])
img[-rightPad:,:,2].fill(median[2])
if topPad > 0:
img[:,:topPad,0].fill(median[0])
img[:,:topPad,1].fill(median[1])
img[:,:topPad,2].fill(median[2])
if bottomPad > 0:
img[:,-bottomPad:,0].fill(median[0])
img[:,-bottomPad:,1].fill(median[1])
img[:,-bottomPad:,2].fill(median[2])
编辑(附加信息):
【问题讨论】:
标签: python numpy image-processing