简单代码
黑白电视噪声图
import cv2 as cv
import numpy as np
while True:
nioseTV=np.random.random((1000,1000,3))#生成1000行1000列的三维数组
nioseTV*=50
nioseTV=nioseTV.round() ##浮点数四舍五入的值
cv.imshow("nioseTv",nioseTV)
if cv.waitKey(1)&0xff==ord('q'):
break
np.random.random((1000,1000,3))详见【转】np.random.random()函数 参数用法以及numpy.random系列函数大全
打印图片第一通道
import cv2 as cv
img=cv.imread("D:/picture/2.jpg")
print(img[:,:,0])
一维图片转化为三维图片
import cv2 as cv
import numpy as np
img=np.mat(np.zeros((300,300),dtype=np.uint8))
#img=np.zeros((300,300),dtype=np.uint8)
img=cv.cvtColor(img,cv.COLOR_GRAY2BGR)
print(img.shape)
将图片转化为python bytearray格式
import cv2 as cv
import numpy as np
image=np.mat(np.zeros((30,30)))
imageByteArray=bytearray(image) #将图片转化为python bytearray格式
#print(imageByteArray)
imageBGR=np.array(imageByteArray).reshape(2000,2000)#重构为[2000,2000]的数组
cv.imshow("imageBGR",imageBGR)
cv.waitKey(0)
cv.destroyAllWindows()
白点与白线
import cv2 as cv
import numpy as np
image=np.zeros((400,400))
image[1,1]=255
cv.imshow("white_dot",image)
image[:,20]=255
image[30,:]=255
cv.imshow("white_line",image)
cv.waitKey(0)
import cv2 as cv
cap=cv.VideoCapture(0)
卷积核
import cv2 as cv
import numpy as np
from scipy import ndimage
image=cv.imread("D:/picture/5.jpg")
image=cv.cvtColor(image,cv.COLOR_BGR2GRAY)
cv.imshow("dsa",image)
kernel33=np.array([[1,1,1],[1,-8,1],[1,1,1]])#[3,3]卷积核
lightimage=ndimage.convolve(image,kernel33)
cv.imshow("lightimage",lightimage)
cv.waitKey(0)
cv.destroyAllWindows()
kernel33=np.array([[1,1,1],[1,-8,1],[1,1,1]])
这个核的作用是减少中心像素的亮度,如果一个像素其周围的像素更加昏暗,它的亮度就会进一步减少。
调用摄像头
import cv2 as cv
def video_demo():
capture = cv.VideoCapture(0)#打开摄像头,0代表的是设备id,如果有多个摄像头,可以设置其他数值
while True:
ret,frame= capture.read() #读取摄像头,它能返回两个参数,第一个参数是bool型的ret,其值为True或False,代表有没有读到图片;第二个参数是frame,是当前截取一帧的图片
frame = cv.flip(frame, 1)#翻转 0:上下颠倒 大于0水平颠倒 小于180旋转
cv.imshow("video", frame)
if cv.waitKey(10) & 0xFF == ord('q'):
break
video_demo()
cv.destroyAllWindows()