关键词搜索

源码搜索 ×
×

Python笔记-安装python虚拟环境及配置opencv及通过opencv识别颜色

发布2020-07-30浏览1597次

详情内容

这里以window为例:

安装python虚拟环境:

安装virtuallenv:

pip install virtualenv

使用cmd进入指定后目录新建虚拟环境

virtualenv env1

这样会生成虚拟环境:

这里使用PyCharm进行配置:

配置好解释器即可。

 

虚拟环境一般package是空的,不会向我上面那样。下面是安装opencv相关的包:

使用腾讯的源安装,这个比较快:

  1. pip install opencv-python -i https://mirrors.cloud.tencent.com/pypi/simple
  2. pip install opencv-contrib-python -i https://mirrors.cloud.tencent.com/pypi/simple

这样就安装好了,就和我上面一样了。

下面是准备好一个像素的素材,来搞个颜色识别的demo

原理是转HSV,在进行识别,以前用C++写过相关原理了,在此不在具体说明

源码如下:

  1. import cv2
  2. if __name__ == '__main__':
  3. matSrc = cv2.imread('C:\\Users\\d5000\\Desktop\\pic\\1.png', cv2.IMREAD_UNCHANGED)
  4. matHsv = cv2.cvtColor(matSrc, cv2.COLOR_BGR2HSV)
  5. if (matHsv[0][0][0] >= 0 and matHsv[0][0][0] <= 180) and (matHsv[0][0][1] > 0 and matHsv[0][0][1] <= 255) and (matHsv[0][0][2] >= 0 and matHsv[0][0][2] <= 46):
  6. print("黑")
  7. pass
  8. elif (matHsv[0][0][0] >= 0 and matHsv[0][0][0] <= 180) and (matHsv[0][0][1] > 0 and matHsv[0][0][1] <= 43) and (matHsv[0][0][2] >= 46 and matHsv[0][0][2] <= 220):
  9. print("灰")
  10. pass
  11. elif (matHsv[0][0][0] >= 0 and matHsv[0][0][0] <= 180) and (matHsv[0][0][1] > 0 and matHsv[0][0][1] <= 30) and (matHsv[0][0][2] >= 221 and matHsv[0][0][2] <= 255):
  12. print("白")
  13. pass
  14. elif ((matHsv[0][0][0] >= 0 and matHsv[0][0][0] <= 10) or (matHsv[0][0][0] >= 156 and matHsv[0][0][0] < 180)) and (matHsv[0][0][1] > 43 and matHsv[0][0][1] <= 255) and (matHsv[0][0][2] >= 46 and matHsv[0][0][2] <= 255):
  15. print("红")
  16. pass
  17. elif (matHsv[0][0][0] >= 11 and matHsv[0][0][0] <= 25) and (matHsv[0][0][1] > 43 and matHsv[0][0][1] <= 255) and (matHsv[0][0][2] >= 46 and matHsv[0][0][2] <= 255):
  18. print("橙")
  19. pass
  20. elif (matHsv[0][0][0] >= 26 and matHsv[0][0][0] <= 34) and (matHsv[0][0][1] > 43 and matHsv[0][0][1] <= 255) and (matHsv[0][0][2] >= 46 and matHsv[0][0][2] <= 255):
  21. print("黄")
  22. pass
  23. elif (matHsv[0][0][0] >= 35 and matHsv[0][0][0] <= 77) and (matHsv[0][0][1] > 43 and matHsv[0][0][1] <= 255) and (matHsv[0][0][2] >= 46 and matHsv[0][0][2] <= 255):
  24. print("绿")
  25. pass
  26. elif (matHsv[0][0][0] >= 78 and matHsv[0][0][0] <= 99) and (matHsv[0][0][1] > 43 and matHsv[0][0][1] <= 255) and (matHsv[0][0][2] >= 46 and matHsv[0][0][2] <= 255):
  27. print("青")
  28. pass
  29. elif (matHsv[0][0][0] >= 100 and matHsv[0][0][0] <= 155) and (matHsv[0][0][1] > 43 and matHsv[0][0][1] <= 255) and (matHsv[0][0][2] >= 46 and matHsv[0][0][2] <= 255):
  30. print("蓝")
  31. pass
  32. elif (matHsv[0][0][0] >= 125 and matHsv[0][0][0] <= 155) and (matHsv[0][0][1] > 43 and matHsv[0][0][1] <= 255) and (matHsv[0][0][2] >= 46 and matHsv[0][0][2] <= 255):
  33. print("紫")
  34. pass
  35. array = matHsv[0:1][0:1][0:3]
  36. print("over")
  37. pass

程序运行截图如下:

第一张

第二张

第三张

 

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载