创建正方形灰度图像,彩色图像,分割图像
import cv2
import numpy as np
import os
# make an array of 120000 random bytes
randomByteArray = bytearray(os.urandom(120000))
flatNumpyArray = np.array(randomByteArray)
# convert the array to make a 400*300 gratscale image
grayImage = flatNumpyArray.reshape(300, 400)
cv2.imwrite("RandomGray.png", grayImage)
# convert the arra to make a 400*100 coloe iamge
bgrImage = flatNumpyArray.reshape(100, 400, 3)
cv2.imwrite("randomColer.png", bgrImage)
#将所有绿色通道设置为0
bgrImage[:,:,1]=0
cv2.imwrite("random2.png",bgrImage)
#通过numpy索引访问原始图像,将第一个区域的值分配给第二个区域
my_roi=grayImage[0:100,0:100]
bgrImage[0:100,0:100]=my_roi
cv2.imwrite("切割.png",bgrImage)
运行
将所有通道绿色通道执为0的图像
随机RGB图像
视屏文件读写
import cv2
videoCapture = cv2.VideoCapture("./video/源视频0.avi")
fps = videoCapture.get(cv2.CAP_PROP_FPS)
size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
videoWriter = cv2.VideoWriter("my_output.avi", cv2.VideoWriter_fourcc('I', '4', '2', '0'),
fps, size)
success, frame = videoCapture.read()
while success:
videoWriter.write(frame)
success, frame = videoCapture.read()
输出了avi文件
捕获摄像头的帧
import cv2
cameraCapture=cv2.VideoCapture(0)
fps=30
size=(int(cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cameraCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
videoWrite=cv2.VideoWriter("new.avi",cv2.VideoWriter_fourcc('I','4','2','0'),
fps,size)
success,fram=cameraCapture.read()
numframsremaining=10*fps-1
while success and numframsremaining>0:
videoWrite.write(fram)
success,fram=cameraCapture.read()
numframsremaining-=1
cameraCapture.release()
因为没有摄像头所以没有结果
生成了文件但是没有图像
在窗口显示图像,等待一个键盘输入关闭所有图像
import cv2
import numpy as np
img=cv2.imread("./randomColer.png")
cv2.imshow('my image',img)
cv2.waitKey()
cv2.destroyAllWindows()
#运行