1 # -*- coding:utf-8 -*-
2 # author:平手友梨奈ii
3 # e-mail:1353593259@qq.com
4 # datetime:2019/10/8 0008 22:31
5 # filename:learncv2.py
6 # software: PyCharm
7
8 import cv2
9 import numpy as np
10
11 """
12 opencv主要用于图像的预处理,例如数据增强
13 """
14
15 # 图片加载,灰度图显示,保存
16 img = cv2.imread('demo.jpg')
17 # cv2.imshow('少女', img)
18 img_grey = cv2.imread('demo.jpg', flags=0)
19 # cv2.imshow('grey', img_grey)
20 # cv2.waitKey(0)
21 cv2.imwrite('result1.jpg', img_grey)
22
23 # 图像显示窗口的创建与销毁
24 cv2.namedWindow('window', flags=cv2.WINDOW_NORMAL) # cv2.WINDOW_NORMAL创建一个大小可以调整的窗口
25 # cv2.imshow('window', img)
26 # cv2.waitKey(0)
27 cv2.destroyWindow('window') # 删除窗口
28 # cv2.destroyAllWindows() # 删除所有已经建立的窗口
29
30 # 图片的基本信息
31 shape1 = img.shape
32 shape2 = img_grey.shape
33 print(shape1) # (675, 1201, 3)
34 print(shape2) # (675, 1201)
35 size1 = img.size
36 size2 = img_grey.size
37 print(size1) # 2432025
38 print(size2) # 810675
39 dtype = img.dtype
40 print(dtype) # uint8 0-256
41
42 img_zero = np.zeros(shape1, dtype=np.uint8)
43 # cv2.imshow('zeros', img_zero)
44 # cv2.waitKey(0)
45
46 # 访问图像中的像素
47 pixel = img[10, 10]
48 print(pixel)
49 img[10:100, 10:100] = [255, 0, 0] # 注意,opencv访问通道的顺序是B,G,R
50 # cv2.imshow('img_modif', img)
51 # cv2.waitKey(0)
52
53 # 像素通道的分离split与合并merge
54 B, G, R = cv2.split(img)
55 # cv2.imshow('Blue', B)
56 # cv2.imshow('Green', G)
57 # cv2.imshow('Red', R)
58 channel_merge = cv2.merge([B, G, R]) # 将其融合为三通道图像
59 print(channel_merge.shape)
60 # cv2.imshow('merge', channel_merge)
61 # cv2.waitKey(0)
62
63 # 给图片上加上文字说明
64 cv2.putText(img, 'hirate yurina', org=(100, 100), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
65 fontScale=1, color=(0, 0, 255))
66 # cv2.imshow('text', img)
67 # cv2.waitKey(0)
68
69 # t图像的缩放
70 resize = cv2.resize(img, (200, 400))
71 cv2.imshow('resize', resize)
72 cv2.waitKey(0)