如何构建具有80%1s和20%0s随机序列的二进制图像?

时间:2019-05-13 04:32:44

标签: python image opencv image-processing

我想用python-opencv实现一种算法,以生成具有80%1s和20%0s随机序列的二进制图像。

1 个答案:

答案 0 :(得分:4)

如果您想使用类似numpy's rand的方法,那么下面的短代码片段应该可以解决问题:

import cv2
import numpy as np

# Generate image with random values
img = np.random.rand(400, 400)

# Binarize image manually, and convert to uint8
img[img <= 0.2] = 0
img[img > 0.2] = 255
img = np.uint8(img)

# Save image, and output white pixel percentage
cv2.imwrite('images/img.png', img)
print("Percentage of white pixels: ", cv2.countNonZero(img) / (400 * 400))

您将获得这样的图像:

Output

//但是,白色像素的百分比可能不完全是80%:

Percentage of white pixels:  0.798975

我想,如果您想精确地将80%的白色像素设置为白色,则必须确定并设置正确的像素数量为白色,并可能以某种方式对其进行混洗,结果结果似乎是随机产生。 编辑:就像Klaus D.在他的评论中建议的那样。

编辑:为完整起见,以下是使用numpy's shuffle方法的代码:

import cv2
import numpy as np

# Generate black image (sequence)
img = np.zeros((400 * 400, 1), np.uint8)

# Determine number of white pixels, and set
img[0:int(0.8 * 400 * 400)] = 255

# Shuffle pixels, and reshape image
np.random.shuffle(img)
img = np.reshape(img, (400, 400))

# Save image, and output white pixel percentage
cv2.imwrite('images/img.png', img)
print("Percentage of white pixels: ", cv2.countNonZero(img) / (400 * 400))

输出图像与上面的图像相同,但是此图像形状的百分比现在正好是0.8:

Percentage of white pixels:  0.8