安装:pip install opencv-python
导入:import cv2
img = cv2.imread("test.jpg")
cv2.imshow("WINDOW",img)
cv2.imwrite("test.jpg", img)
video = cv2.VideoCapture("test.mp4")
cap = cv2.VideoCapture(0)
cap.set(3,640) ## Frame width
cap.set(4,480) ## Frame Height
cap.set(10,100) ## Brightness
while True:
success, img = cap.read()
cv2.imshow("Video",img)
if cv2.waitKey(1) & 0xff == ord('q'):
break
imgBlack = np.zeros([640, 480], dtype=np.uint8)
imgWhite = ~imgBlack
imgResized = cv2.resize(img,(224,224))
imgCropped = img[50:250,120:330]
imgFlip = cv2.flip(img, 1) # > 0: 左右翻转
imgFlip = cv2.flip(img, 0) # == 0: 上下翻转
imgFlip = cv2.flip(img, -1) # < 0: 中心翻转(旋转180度)
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgHsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
b,g,r = cv2.split(img)
img = cv2.merge((b,g,r))
'''
BORDER_REPLICATE:复制法,也就是复制最边缘像素
BORDER_REFLECT:反射法,对感兴趣的图像中的像素在两边进行复制,fedcba|abcdefgh|hgfedcb
BORDER_REFLECT_101:反射法,也就是以最边缘像素为轴,对称,gfedcb|abcdefgh|gfedcba
BORDER_WRAP:外包装法,cdefgh|abcdefgh|abcdefg
BORDER_CONSTANT:常量法,常数值填充
'''
top_size,bottom_size,left_size,right_size = (5,5,5,5)
replicate = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, borderType=cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size,cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_WRAP)
constant = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size,cv2.BORDER_CONSTANT, value=0)
img= cv2.addWeighted(img1, 0.4, img2, 0.6, 0)
imgBlur = cv2.blur(img, (3, 3))
imgBlur = cv2.boxFilter(img,-1,(3,3), normalize=False)
imgBlur = cv2.GaussianBlur(img,(3,3),0)
imgBlur = cv2.medianBlur(img, 5)
'''
ret, dst = cv2.threshold(src, thresh, maxval, type)
src: 输入图,只能输入单通道图像,通常来说为灰度图
dst: 输出图
thresh: 阈值
maxval: 当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值
type:二值化操作的类型,包含以下5种类型:
cv2.THRESH_BINARY 超过阈值部分取maxval(最大值),否则取0
cv2.THRESH_BINARY_INV THRESH_BINARY的反转
cv2.THRESH_TRUNC 大于阈值部分设为阈值,否则不变
cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0
cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转
'''
ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
ret, thresh = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
img = cv2.add(img1, img2)
img = cv2.subtract(img1, img2)
img = cv2.multiply(img1, img2)
img = cv2.divide(img1, img2)
'''
cv2.calcHist(images,channels,mask,histSize,ranges)
images: 原图像图像格式为 uint8 或 float32。当传入函数时应 用中括号 [] 括来例如[img]
channels: 同样用中括号括来它会告函数我们统幅图 像的直方图。如果入图像是灰度图它的值就是 [0]如果是彩色图像 的传入的参数可以是 [0][1][2] 它们分别对应着 BGR。
mask: 掩模图像。统整幅图像的直方图就把它为 None。但是如 果你想统图像某一分的直方图的你就制作一个掩模图像并 使用它。
histSize:BIN 的数目。也应用中括号括来
ranges: 像素值范围常为 [0,256]
'''
hist = cv2.calcHist([img],[0],None,[256],[0,256]) # (256, 1)
plt.hist(img.ravel(),256);
plt.show()
# 三通道直方图
color = ('b','g','r')
for i,col in enumerate(color):
histr = cv2.calcHist([img],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
#彩色图像均衡化
(b, g, r) = cv2.split(img_test1)
bH = cv2.equalizeHist(b)
gH = cv2.equalizeHist(g)
rH = cv2.equalizeHist(r)
#合并每一个通道
result = cv2.merge((bH, gH, rH))
'''
dst = cv2.Sobel(src, ddepth, dx, dy, ksize)
ddepth:图像的深度
dx和dy分别表示水平和竖直方向
ksize:Sobel算子的大小
'''
# 分别计算x、y方向梯度,再合并
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
# 同时计算x、y梯度(不建议)
sobelxy=cv2.Sobel(img,cv2.CV_64F,1,1,ksize=3)
sobelxy = cv2.convertScaleAbs(sobelxy)
scharrx = cv2.Scharr(img,cv2.CV_64F,1,0)
scharry = cv2.Scharr(img,cv2.CV_64F,0,1)
scharrx = cv2.convertScaleAbs(scharrx)
scharry = cv2.convertScaleAbs(scharry)
scharrxy = cv2.addWeighted(scharrx,0.5,scharry,0.5,0)
laplacian = cv2.Laplacian(img,cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
#imgCanny = cv2.Canny(img,threshold1,threshold2)
imgCanny = cv2.Canny(img,100,150)
up = cv2.pyrUp(img) # (442, 340, 3) --> (884, 680, 3)
down = cv2.pyrDown(img)
down = cv2.pyrDown(img)
up = cv2.pyrUp(down)
kernel = np.ones((5,5),np.uint8)
imgDialation = cv2.dilate(imgCanny,kernel,iterations=1) ##DIALATION
imgErosion = cv2.erode(imgCanny,kernel,iterations=1) ##EROSION
kernel = np.ones((5,5),np.uint8)
imgOpen = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
imgClose = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
kernel = np.ones((5,5),np.uint8)
imgTophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
imgBlackhat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT, kernel)
#cv2.rectangle(img,(w,h),(x,y),(R,G,B),THICKNESS)
cv2.rectangle(img,(100,300),(200,300),(255,0,255),2)
#cv2.circle(img,(x,y),radius,(R,G,B),THICKNESS)
cv2.circle(img,(200,130),90,(255,255,0),2)
#cv2.line(img,(x1,y1),(x2,y2),(R,G,B),THICKNESS)
cv2.line(img,(110,260),(300,260),(0,255,0),3)
#cv2.putText(img,text,(x,y),FONT,FONT_SCALE,(R,G,B),THICKNESS)
cv2.putText(img,"HELLO",(120,250),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)
# 更高的准确率,使用二值图像。
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 计算出嵌套轮廓
binary, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# 传入绘制图像,轮廓,轮廓索引(-1全部),颜色模式,线条厚度
draw_img = img.copy() # 注意需要copy,要不原图会变
res = cv2.drawContours(draw_img, contours, -1, (0, 0, 255), 2)
cnt = contours[0]
area = cv2.contourArea(cnt) # 面积
length = cv2.arcLength(cnt,True) # 周长,True表示闭合
x,y,w,h = cv2.boundingRect(cnt) # 外接矩形
(x,y), radius = cv2.minEnclosingCircle(cnt) # 外接圆
'''
cv2.matchTemplate(img, template, cv2.TM_SQDIFF)
TM_SQDIFF:计算平方不同,计算出来的值越小,越相关
TM_CCORR:计算相关性,计算出来的值越大,越相关
TM_CCOEFF:计算相关系数,计算出来的值越大,越相关
TM_SQDIFF_NORMED:计算归一化平方不同,计算出来的值越接近0,越相关
TM_CCORR_NORMED:计算归一化相关性,计算出来的值越接近1,越相关
TM_CCOEFF_NORMED:计算归一化相关系数,计算值越接近1,越相关
'''
res = cv2.matchTemplate(img, template, cv2.TM_SQDIFF)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
'''
cv2.cornerHarris(img, blockSize, ksize, k)
img:数据类型为 float32 的入图像
blockSize:角点检测中指定区域的大小
ksize:Sobel求导中使用的窗口大小
k:取值参数为 [0,04,0.06]
'''
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dst = cv2.cornerHarris(gray, 2, 3, 0.04)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 得到特征点
sift = cv2.xfeatures2d.SIFT_create()
kp = sift.detect(gray, None)
# 显示特征点
img = cv2.drawKeypoints(gray, kp, img)
# 计算特征
kp, des = sift.compute(gray, kp)