目录
import cv2
# 生成图片
img = cv2.imread(r'C:\Users\Desktop\test1.jpg')
# 生成灰色图片
imgGrey = cv2.imread("1.jpg", 0)
# 展示原图
cv2.imshow("img", img)
# 展示灰色图片
#cv2.imshow("imgGrey", imgGrey)
# 等待图片的关闭
cv2.waitKey(0)
# 保存灰色图片
#cv2.imwrite("Copy.jpg", imgGrey)
cv2.namedWindow(窗口名,属性) 创建一个窗口,属性—指定窗口大小模式:
cv2.WINDOW_AUTOSIZE:根据图像大小自动创建大小
cv2.WINDOW_NORMAL:窗口大小可调整
cv2.destoryAllWindows(窗口名) 删除任何建立的窗口
import cv2
# 生成图片
img = cv2.imread(r'C:\Users\Desktop\test1.jpg')
cv2.namedWindow("img", cv2.WINDOW_NORMAL)
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
img.shape 返回图像高(图像矩阵的行数)、宽(图像矩阵的列数)和通道数3个属性组成的元组,若图像是非彩色图,则只返回高和宽组成的元组。
import cv2
img = cv2.imread(r'C:\Users\Desktop\test1.jpg')
imgGray = cv2.imread(r'C:\Users\Desktop\test1.jpg', 0)
print('****img*****)
print( img.shape)
print('width: ', img.shape[0])
print('heigh: ', img.shape[1])
print('channel: ', img.shape[2])
print('\n\n***imgGray**')
print(imgGray.shape)
print('width: ', imgGray.shape[0])
print('heigh: ', imgGray.shape[1])
print('channel: ', imgGray.shape[2])
图像矩阵img的size属性和dtype分别对应图像的像素总数目和图像数据类型。一般情况下,图像的数据类型是uint8。
import cv2
img = cv2.imread(r'C:\Users\Desktop\test1.jpg')
print('图像类型: ', type(img))
print('图像像素点数: ', img.size)
print('图像像素灰度值类型:', img.dtype)
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\Desktop\test1.jpg')
imgZero = np.zeros(img.shape, np.uint8)
imgFix = np.zeros((300, 500, 3), np.uint8)
cv2.imshow("imgZero", imgZero)
cv2.imshow("imgFix", imgFix)
cv2.waitKey()
OpenCV中图像矩阵的顺序是B、G、R。可以直接通过坐标位置访问和操作图像像素。
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\Desktop\test1.jpg')
pixel_50_100 = img[50, 100]
#返回3个值,分别是该像素点在BGR通道的值
print(pixel_50_100)
img[50, 100] = (0, 0, 255)
cv2.imshow("img", img)
cv2.waitKey()
分开访问图像某一通道像素值也very方便
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\Desktop\test1.jpg')
img[0:100, 100:200, 0] = 255
img[100:200, 200:300, 1] = 255
img[200:300, 300:400, 2] = 255
cv2.imshow("img", img)
cv2.waitKey()
更改图像某一矩形区域的像素值也很方便:
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\Desktop\test1.jpg')
img[0:50, 1:100] = (0, 0, 255)
cv2.imshow("img", img)
cv2.waitKey()
import cv2
import numpy as np
img = cv2.imread(r'C:\Users\Desktop\test1.jpg')
b, g, r = cv2.split(img)
# b = cv2.split(img)[0]
# g = cv2.split(img)[1]
# r = cv2.split(img)[2]
merged = cv2.merge([b, g, r])
cv2.imshow("Blue", b)
cv2.imshow("Green", g)
cv2.imshow("Red", r)
cv2.imshow("Merged", merged)
cv2.waitKey()
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
for i in range(0, 19):
print(cap.get(i))
while(1):
ret, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_blue = np.array([100, 47, 47])
upper_blue = np.array([124, 255,255])
mask = cv2.inRange(hsv, lower_blue, upper_blue) #蓝色掩模
res = cv2.bitwise_and(frame, frame, mask = mask)
cv2.imshow(u"Capture", frame)
cv2.imshow(u"mask", mask)
cv2.imshow(u"res", res)
key = cv2.waitKey(1)
if key & 0xff == ord('q') or key == 27:
print(frame.shape,ret)
break
cap.release()
cv2.destroyAllWindows()