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

大家一起学机器学习啦!

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

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

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

3.创建随机图像

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

import cv2
import numpy as np
fn = "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()#关闭所有窗口
效果图:



发布了24 篇原创文章 · 获赞 88 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/SoHardToNamed/article/details/78522623
今日推荐