赞
踩
在opencv的C++代码中,表示图像有专门的结构cv::Mat,在python中有numpy工具可以使用。
cv2.imread(path_of_image, intflag)
标记intflag的格式:
- cv2.IMREAD_COLOR: 加载
彩色图像
。任何图像的透明度都将被忽略。它是默认标志- cv2.IMREAD_GRAYSCALE:以
灰度
模式加载图像- cv2.IMREAD_UNCHANGED:保留读取图片
原有的颜色
通道
- 1 :等同于cv2.IMREAD_COLOR
- 0 :等同于cv2.IMREAD_GRAYSCALE
- -1 :等同于cv2.IMREAD_UNCHANGED
import cv2 file_path = "../../pic/pic_1.png" #图片相对位置 #读取图像 img = cv2.imread(file_path) #显示图像 cv2.imshow("image", img) #名字和显示的对象 #保存图像 cv2.imwrite('new_image.png',img) # 指定jpg质量,范围从1~100,默认95,值越高画质越好,文件越大 cv2.imwrite('good_img.jpg',img,(cv2.IMWRITE_JPEG_QUALITY,100)) # 等待键盘输入,为毫秒级 cv2.waitKey(0)
输出:
使用shape方法,可以获取图像的height、width和channels的值。
height = img.shape[0] #将img中的元素取出,赋值给height,width,channels
width = img.shape[1]
channels = img.shape[2]
下列代码展示了怎么绘制线段、矩形、圆形等简单元素。
import cv2 import numpy as np img = np.ones((512,512,3), np.uint8) height = img.shape[0] #将img中的元素取出,赋值给height,width,channels width = img.shape[1] channels = img.shape[2] print(width, height, channels) # 512 * 512 * 3 img = 255*img # 白色 img = cv2.line(img, (100,100), (400,400),(255, 0, 0), 5) img = cv2.rectangle(img,(200, 20),(400,120),(0,255,0),3) img = cv2.circle(img,(100,400), 50, (0,0,255), 2) img = cv2.circle(img,(250,400), 50, (0,0,255), 0) img = cv2.ellipse(img,(256,256),(100,50),0,0,180,(0, 255, 255), -1) pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32) img = cv2.polylines(img,[pts],True,(0, 0, 0), 2) cv2.imshow('img', img) #cv2.imwrite("1.png",img),保存图像 #当指定waitKey(0) == 27时当敲击键盘 Esc 时便销毁所有窗口 if cv2.waitKey(0) == 27: cv2.destroyAllWindows()
显示结果如下:
下面我们以一个将图像元素取反的例子为例,说明怎么实现元素的遍历。
import cv2 as cv import numpy as np def access_pixels(frame): print(frame.shape) #shape内包含三个元素:按顺序为高、宽、通道数 height = frame.shape[0] weight = frame.shape[1] channels = frame.shape[2] print("weight : %s, height : %s, channel : %s" %(weight, height, channels)) for row in range(height): #遍历高 for col in range(weight): #遍历宽 for c in range(channels): #便利通道 pv = frame[row, col, c] frame[row, col, c] = 255 - pv #全部像素取反,实现一个反向效果 cv.imshow("fanxiang", frame) file_path = "../../pic/pic_1.png" #图片相对位置 src = cv.imread(file_path) cv.imshow("Picture", src) access_pixels(src) cv.waitKey(0)
图像像素取反后的效果如下图所示
在OpenCV中,颜色模式的默认设置顺序为BGR
,而 Matplotlib则是用我们熟悉的RGB模式来显示图像的
,所以如果不对颜色模式进行转换直接将图像显示出来,那显示的图像将不是我们原本想要获取的。下例展示了使用cvtColor
转换图像颜色后,使用matplotlib显示。
import numpy as np
from matplotlib import pyplot as plt
import cv2
file_path = "../../pic/pic_1.png" #图片相对位置
#读取图像
img = cv2.imread(file_path)
#图像转换,将BGR转换为RGB
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
#matplotlib显示图像
plt.imshow(img)
plt.show()
输出:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。