当前位置:   article > 正文

Python 18.opencv 轮廓相关,凸包检测,外接矩形、圆,极点,平均颜色,轮廓内像素点_计算外接圆内颜色平均值

计算外接圆内颜色平均值
  1. import cv2
  2. import numpy as np
  3. img = cv2.imread('pic5.PNG')
  4. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  5. ret, thresh = cv2.threshold(gray, 127, 255, 0)
  6. contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  7. img = cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
  8. # img = cv2.drawContours(img, contours, 3, (0, 255, 0), 3)
  9. # 获取图像的矩,可以计算出对象的重心
  10. cnt = contours[0]
  11. M = cv2.moments(cnt)
  12. print(M)
  13. # 获取轮廓的面积
  14. area = cv2.contourArea(cnt)
  15. print(area)
  16. # 获取轮廓周长
  17. perimeter = cv2.arcLength(cnt, True)
  18. print(perimeter)
  19. # 轮廓近似(获取最大轮廓),如带缺口的矩形识别成矩形
  20. epsilon = 0.1*cv2.arcLength(cnt, True)
  21. approx = cv2.approxPolyDP(cnt, epsilon, True)
  22. # 凸包, 凸检验
  23. # 获取凸包
  24. hull = cv2.convexHull(cnt)
  25. # 检测是否是凸包
  26. k = cv2.isContourConvex(cnt)
  27. print(k)
  28. # 边界矩形,因为我的矩形轮廓所以无效果
  29. # 直边界矩形,未考虑旋转
  30. x, y, w, h = cv2.boundingRect(cnt)
  31. img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
  32. # 旋转的边界矩形,考虑对象旋转
  33. x, y, w, h = cv2.boundingRect(cnt)
  34. img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
  35. # 边界矩形的长宽比
  36. aspect_ratio = float(w)/h
  37. # 边界矩形的面积
  38. # 轮廓面积与凸包面积的比
  39. hull_area = cv2.contourArea(hull)
  40. solidity = float(area)/hull_area
  41. # 返回对象的方向,长轴和短轴的长度,有问题
  42. # (x, y), (MA, ma), angle = cv2.fitEllipse(cnt)
  43. # 最小外接圆
  44. (x, y), radius = cv2.minEnclosingCircle(cnt)
  45. center = (int(x), int(y))
  46. radius = int(radius)
  47. #img = cv2.circle(img, center, radius, (0, 255, 0), 2)
  48. # 椭圆拟合,注意椭圆不要超出图像边界,可能报错
  49. #ellipse = cv2.fitEllipse(cnt)
  50. #img = cv2.ellipse(img, ellipse, (0, 255, 0), 2)
  51. # 直线拟合
  52. rows, cols = img.shape[:2]
  53. [vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)
  54. lefty = int((-x*vy/vx) + y)
  55. righty = int(((cols - x)*vy/vx)+y)
  56. # img = cv2.line(img, (cols-1, righty), (0, lefty), (0, 255, 0), 2)
  57. # 获取构成对象的所有像素点
  58. mask = np.zeros(gray.shape, np.uint8)
  59. cv2.drawContours(mask, [cnt], 0, 255, -1)
  60. pixelpoints = np.transpose(np.nonzero(mask))
  61. print(pixelpoints)
  62. # 最大值最小值及它们的位置
  63. min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(gray, mask=mask)
  64. # 获取图像的平均颜色及平均灰度
  65. mean_val = cv2.mean(img, mask=mask)
  66. print(mean_val)
  67. # 极点-轮廓的最左右上下的点
  68. leftmost = tuple(cnt[cnt[:, :, 0].argmin()][0])
  69. rightmost = tuple(cnt[cnt[:, :, 0].argmax()][0])
  70. topmost = tuple(cnt[cnt[:, :, 1].argmin()][0])
  71. bottommost = tuple(cnt[cnt[:, :, 1].argmax()][0])
  72. cv2.imshow("img", mask)
  73. cv2.waitKey(0)
  74. cv2.destroyAllWindows()

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/79032
推荐阅读
相关标签
  

闽ICP备14008679号