Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

20.6. OpenCV

20.6.1. 安装 OpenCV

		
pip3 install opencv-python		
		
		

显示版本

		
import cv2
print(cv2.__version__)		
		
		

20.6.2. 显示图片

		
import cv2 as cv

src = cv.imread("me.jpeg")
cv.namedWindow("Picture", cv.WINDOW_AUTOSIZE)
cv.imshow("Picture", src)
cv.waitKey(0)
# 关闭所有窗口
cv.destroyAllWindows()		
		
		

20.6.3. 将BGR图像转为RGB

		
import cv2
import matplotlib.pyplot as plt

# 读取图像
# img = cv2.imread('path_to_image.jpg')
img = cv2.imread('test/test.png')

# 将BGR图像转为RGB
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# 使用matplotlib显示图像
plt.imshow(img_rgb)
plt.axis('off')  # 不显示坐标轴
plt.show()	
		
		

20.6.4. uint8 格式

		
import cv2

filePath="Dataset/FFHQ/00000.png"
img=cv2.imread(filePath)
print(f"img.shape = {img.shape}")     	# img.shape = (128, 128, 3)
print(f"img = {img}")     				# img.dtype = uint8

"""
img = [[[146 130   0]
  [144 128   0]
  [141 125   0]
  ...
  [164 162 133]
  [159 157 133]
  [163 157 134]]]
"""
		
		

20.6.5. 应用Canny边缘检测

		
import cv2

# 加载图像
img = cv2.imread('path_to_image.jpg', 0)  # 0表示以灰度模式读取

# 应用Canny边缘检测
edges = cv2.Canny(img, 100, 200)

# 显示结果
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()		
		
		

20.6.6. 摄像头捕捉图像

		
import cv2 as cv

capture = cv.VideoCapture(1)
while (True):
    # ret为返回值,frame为视频的每一帧
    ret, frame = capture.read()
    cv.imshow("video", frame)
    c = cv.waitKey(50)
    # 按了esc候可以退出
    if c == 27:
        break		
		
		

20.6.7. imread()

		
import cv2 as cv

image = cv.imread("me.jpeg")

print(type(image))  # 类别
print(image.shape)  # 高,宽,通道数目
print(image.size)   # 像素数据,上面三个属性的乘积
print(image.dtype)