python模块opencv之图片操作(1)

来源:互联网 发布:外贸客户搜索软件 编辑:程序博客网 时间:2024/06/11 02:15

大家一起学机器学习啦!

图片操作太多了,这里包括了

1.图片的读入(imread())

2.获取图像大小(.shape)

3.创建随机图像

4.图像色彩的调节和输出水印。

import cv2import numpy as npfn = "Imread.jpg"'''Img基本操作'''print("loadin %s ..." % fn)img1 = cv2.imread(fn)#读入照片print(img1.shape)#获取图像矩阵大小print(img1[300, 300,:])#像素值'''创建随机图像'''sz1 = 200#图像行像素点sz2 = 300#图像列像素点print(u'产生空图像矩阵(%d * %d) ...' % (sz1, sz2))img2 = np.zeros((sz1, sz2, 3), np.uint8)pos1 = np.random.randint(200, size = (2000, 1))#行位置随机数组pos2 = np.random.randint(300, size = (2000, 1))#列位置随机数组for i in range(2000):#在随机位置处设置像素点值    img2[pos1[i], pos2[i], [0]] = np.random.randint(0, 255)    img2[pos1[i], pos2[i], [1]] = np.random.randint(0, 255)    img2[pos1[i], pos2[i], [2]] = np.random.randint(0, 255)'''调节图像亮度'''#实现日落效果的原理,只需把蓝色值和绿色值设为原来的70%#实现负片的原理是把三色值设为(255 - 原值)img3 = cv2.imread(fn)w = img3.shape[1]h = img3.shape[0]for xi in range(0, w):    for xj in range(0, h):        img3[xj, xi, 0] = int(img3[xj, xi, 0] * 0.2)#亮度变为原来的20%        img3[xj, xi, 1] = int(img3[xj, xi, 1] * 0.2)        img3[xj, xi, 2] = int(img3[xj, xi, 2] * 0.2)'''输出水印'''img4 = cv2.imread(fn)cv2.putText(img4, "Machine learning", (20, 50), cv2.FONT_HERSHEY_PLAIN, 2.0, (0, 0, 0), thickness=2)cv2.imshow('preview1', img1)#显示照片,'preview1'是显示窗口名cv2.imshow('preview2', img2)cv2.imshow('preview3', img3)cv2.imshow('preview4', img4)cv2.waitKey()#等待按键cv2.destroyAllWindows()#关闭所有窗口
效果图:



阅读全文
1 0