OpenCV学习笔记(附1)——椒盐图生成
- 蒙面西红柿
- 2,156
根据最近的学习需求创建了一个自动生成椒盐图Python程序。后续还有改进空间。
import cv2
import numpy as np
img_name = "Lenna.jpg"
if __name__ == '__main__':
print ("load %s..." %img_name)
img = cv2.imread(img_name)
count = int(img.shape[0]*img.shape[1]/200)
print("椒盐数:%d" %count)
for k in range(0, count):
#get the random point
xi = int(np.random.uniform(0, img.shape[1]))
xj = int(np.random.uniform(0, img.shape[0]))
#如果是灰度图
if img.ndim == 2:
index = np.random.randint(0,2)
#生成椒
if index == 0:
img[xj, xi] = 255
#生成盐
else:
img[xj, xi] = 0
#如果是BGR图
elif img.ndim == 3:
index = np.random.randint(0,2)
#生成椒
if index == 0:
img[xj,xi,0] = 25
img[xj,xi,1] = 20
img[xj,xi,2] = 20
#生成盐
else:
img[xj,xi,0] = 255
img[xj,xi,1] = 255
img[xj,xi,2] = 255
cv2.imshow("img", img)
cv2.imwrite("LennaNoise.jpg", img)
cv2.waitKey()
cv2.destroyAllWindows()
文章评论