OpenCV基本I/O

读/写图像文件

OpenCV的imread()和imwrite()函数能支持各种静态图像文件格式。

可读取一种格式的图像文件,保存成另一种格式:

import cv2

image = cv2.imread('MyPic.png')
cv2.imwrite('MyPic.jpg', image)

将加载的PNG文件转换为灰度图像:

import cv2

grayImage = cv2.imread('MyPic.png', cv2.IMREAD_GRAYSCALE)
cv2.imwrite('MyGrayPic.png', grayImage)

图像与原始字节之间的转换

将含有随机字节的bytearray转换为灰度图像和BGR图像:

import cv2
import numpy
import os

# Make an array of 120000 randoms bytes.
randomByteArray = bytearray(os.urandom(120000))
flatNumpyArray = numpy.array(randomByteArray)

# Convert the array to make a 400x300 grayscale image.
grayImage = flatNumpyArray.reshape(300,400)
cv2.imwrite('RandomGray.png',grayImage)

# convert the array to make a 400x100 color image.
bgrImage = flatNumpyArray.reshape(100,400,3)
cv2.imwrite('RandomColor.png',bgrImage)

使用numpy.array访问图像数据

将BGR图像在(0,0)处的像素变为白像素:

import cv2
import numpy as np

image = cv2.imread('MyPic.png')
image[0,0] = [255,255,255]

进一步调用imread函数显示图像,可以看到图像左上角有一个白点

将坐标(150,120)的当前蓝色值(127)变为255:

import cv2
import numpy as np

image = cv.imread('MyPic.png')
print(img.item(150,120,0))#三元组:x,y,索引
image.itemset((150,120,0),255)
print(image.item(150,120,0))

实时显示摄像头:

import cv2

clicked = False
def onMouse(event,x,y,flags,para):
    global clicked
    if event == cv2.EVENT_LBUTTONUP:
        clicked = True

cameraCapture = cv2.VideoCapture(0)
cv2.namedWindow('MyWindow')
cv2.setMouseCallback('MyWindow',onMouse)

print('Showing camera feed.Click window or press any key to stop.')
success,frame = cameraCapture.read()
while success and cv2.waitKey(1) == -1 and not clicked:
    cv2.imshow('MyWindow',frame)
    success,frame = cameraCapture.read()

cv2.destroyWindow('MyWindow')
cameraCapture.release()

你可能感兴趣的:(OpenCV&图像处理)