【杂记】机器视觉 #opencv #numpy #matplotlib
1、开运算
开运算就是先腐蚀再膨胀的去除噪点活动
2、设置掩膜的时候,bgr转hsv用到的inRange里的上下限范围要用到ndarray格式
3、opencv读取颜色并非RGB而是BGR格式,必要时要转义
import cv2
import numpy as np
import matplotlib.pyplot as plt
img=cv2.imread('san2.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_r =np.zeros_like(img)
img_g =np.zeros_like(img)
img_b =np.zeros_like(img)
R=img[:,:,0]
G=img[:,:,1]
B=img[:,:,2]
img_r[:,:,0]=R
img_g[:,:,1]=G
img_b[:,:,2]=B
plt.subplot(232)
plt.imshow(img)
plt.subplot(234)
plt.imshow(img_r)
plt.subplot(235)
plt.imshow(img_g)
plt.subplot(236)
plt.imshow(img_b)
plt.show()
4、计算机识别图片的坐标是横向x,纵向y(下为正方向),和三维数组的表示不同,三维数组的axis=0为纵向,1为横向
案例
5、二值化的threshold函数在调用时返回值有两个要注意,一个是阈值一个是图片的多维数组
6、框选图片区域获取颜色并且显示字体,putText函数
import cv2
img=cv2.imread('./win.png')
x,y,w,h=cv2.selectROI('1',img)
m=img[y:y+h,x:x+w]
img_blur=cv2.GaussianBlur(m,(5,5),0)
img_hsv=cv2.cvtColor(img_blur,cv2.COLOR_BGR2HSV)
colors=[]
yellow_count = blue_count = green_count =white_count=0
for i in range(h):
for j in range(w):
H,S,V=img_hsv[i,j]
if 11<=H<=34 and S>43:
yellow_count+=1
elif 35<=H<=99 and S>43:
green_count+=1
elif 100<=H<=124 and S>43:
blue_count+=1
elif 0<=H<=180 and S<30:
white_count+=1
color='no'
if yellow_count*2>=w*h:
color='yellow'
elif green_count*2>=w*h:
color='green'
elif blue_count*2>=w*h:
color='blue'
elif white_count*2>=w*h:
color='white'
img_t=cv2.putText(
m,
color,
(h//3,w//3),
cv2.FONT_HERSHEY_SIMPLEX,
1.5,
(0,0,0),
2
)
cv2.imshow('0',img_t)
cv2.waitKey(0)