简体   繁体   English

用NumPy填充图像会全黑

[英]Padding an image with NumPy returns it all black

I use NumPy to create a new 2D array with 0 on the border and the array of the original image inside. 我使用NumPy创建一个新的2D数组,其边界为0,内部为原始图像的数组。 I print the new array, it's what I expect. 我打印了新数组,这就是我所期望的。 But when I plot it, it's all black. 但是当我绘制它时,它全都是黑色的。

I tried for-loop and NumPy, it's useless. 我尝试了for-loop和NumPy,这没用。

import cv2
import numpy as np

path = 'test.jpg'
img = cv2.imread(path,0)

print(img)
height,width = img.shape       # 440 * 455

new_arr = np.zeros((height+2,width+2), dtype = int)

#for i in range(height):
#   for j in range(width):
#      new_arr[i+1][j+1] = img[i][j]

new_arr[1:height+1,1:width+1] = img
print(new_arr)


cv2.imshow('new image',new_arr)
cv2.waitKey(0)
cv2.destroyAllWindows()

The original image is here: 原始图片在这里:

原始图像

I expect an image with black border (just 1 pixel), and the inside is the original image to do median filtering, but the actual output is a black image. 我希望图像具有黑色边框(仅1像素),内部是进行中间值滤波的原始图像,但实际输出是黑色图像。

Not sure how you are getting black image, as your code should throw an error. 不确定您如何获得黑色图像,因为您的代码应引发错误。 You need to set dtype value in proper namespace ( np. ) and the value should be uint8 : 您需要在适当的名称空间( np. )中设置dtype值,并且该值应为uint8

import cv2
import numpy as np

path = 'test.png'
img = cv2.imread(path,0)

height,width = img.shape

new_arr = np.zeros((height+2,width+2), dtype = np.uint8)

new_arr[1:height+1,1:width+1] = img
print(new_arr)

cv2.imshow('new image',new_arr)
cv2.waitKey(0)
cv2.destroyAllWindows()

Please note that the image you have given is png , not jpg . 请注意 ,您提供的图像是png而不是jpg Code tested on that image. 在该图像上测试了代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM