我可以将RGB图像转换为二进制,但其尺寸仍然太大(1280x720x3)
。由于二进制图像的每个像素只有0或1的值,我想将其尺寸减小到(1280x720x1)
,因此我不必处理内存问题(因为我正在使用数千个图像)
import cv2
import glob
def convert_to_binary(source_path, destination_path):
i = 0
for filename in glob.iglob("{}*.png".format(source_path)):
im_gray = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
cv2.imwrite("{}.png".format(destination_path + str(i)), im_bw)
i += 1
如何修改上述代码,将已保存图片的尺寸从(1280x720x3)
更改为(1280x720x1)
?
答案 0 :(得分:1)
使用private route: ActivatedRoute | any
或np.newaxis
将(H,W)转换为(H,W,1)。
np.reshape
(1)使用np.newaxis添加新维度
>>> h,w = 3,4
>>> binary = np.zeros((h,w))
>>> binary.shape
(3, 4)
(2)使用重塑来改变维度
>>> new_binary = binary[..., np.newaxis]
>>> new_binary.shape
(3, 4, 1)
>>>
现在看结果。
>>> new_binary2 = binary.reshape((h,w,1))
>>> new_binary2.shape
(3, 4, 1)
答案 1 :(得分:0)
从各种来源,这是将rgb转换为灰度的一种化身。
# num_92 gray scale image from rgb
def num_92():
"""num_92... gray-scale image from rgb
:Essentially gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
: np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
: http://stackoverflow.com/questions/12201577/how-can-i-convert
: -an-rgb-image-into-grayscale-in-python
: https://en.m.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
: see https://en.m.wikipedia.org/wiki/HSL_and_HSV
"""
frmt = """
:---------------------------------------------------------------------:
{}
:---------------------------------------------------------------------:
"""
import matplotlib.pyplot as plt
a = np.arange(256).reshape(16, 16)
b = a[::-1]
c = np.ones_like(a)*128
rgb = np.dstack((a, b, c))
gray = np.dot(rgb[..., :3], [0.2989, 0.5870, 0.1140])
plt.imshow(gray, cmap=plt.get_cmap('gray'))
plt.show()
args = [num_92.__doc__]
print(frmt.format(*args))
重命名def,但在此期间,请使用
调用它num_92()
或玩部分
import matplotlib.pyplot as plt
a = np.arange(256).reshape(16, 16)
b = a[::-1]
c = np.ones_like(a)*128
rgb = np.dstack((a, b, c))
plt.imshow(rgb, cmap=plt.get_cmap('hot'))
plt.show()
但是如果你对重新缩放的rgb取平均值会得到不同的图片,那么这取决于你想要的内容
avg = np.average(rgb, axis=-1)
avg.shape
(16, 16)
plt.imshow(avg, cmap=plt.get_cmap('gray'))
plt.show()