尝试检测ci中心的颜色时出错

2024-04-24 00:53:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从HoughCircles检测到的圆的中心的颜色。我的做法如下:

print("Center of the circle: ", i[0]," ", i[1])
print(ci[i[0]][i[1]][0]," blue")
print(ci[i[0]][i[1]][1]," green")
print(ci[i[0]][i[1]][2]," red")

这里ci是opencv图像数组,i[0]i[1]表示圆的中心坐标,如下面给出的代码中HoughCircles所示。你知道吗

但当我这么做的时候,我得到了一个错误的说法。你知道吗

IndexError: index 1034 is out of bounds for axis 0 with size 600

我不明白为什么会这样。我在试着检测圆心的颜色。你知道吗

    import cv2
    import numpy as np
    import sys
    import math


    img = cv2.imread("images/diffc.jpeg", 0)
    ci = cv2.imread("images/diffc.jpeg")

    cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)



    minDist = 150
    param1 = 120
    param2 = 37

    minRadius = 120
    maxRadius = 140


    circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,minDist,
                                param1=param1,param2=param2,minRadius=minRadius,maxRadius=maxRadius)


    if circles is None:
            print("No circles detected!")
            sys.exit(-1)


    circles = np.uint16(np.around(circles))

    for i in circles[0,:]:

        # draw the outer circle
        cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
        # draw the center of the circle
        cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
        print("Center of the circle: ", i[0]," ", i[1])
        # STATEMENTS THAT THROW ERROR
        print(ci[i[0]][i[1]][0]," blue")
        print(ci[i[0]][i[1]][1]," green")
        print(ci[i[0]][i[1]][2]," red")

    cv2.imshow('detected circles',cimg)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

图片如下: Image


Tags: oftheimportciimgnpcv2param1
1条回答
网友
1楼 · 发布于 2024-04-24 00:53:23

这里您需要知道HoughCircles方法以width x height的形式返回圆心,numpyrows x columns查找图像。你知道吗

所以需要先传递columns,然后在ci中传递rows。你知道吗

所以要检测蓝色:ci[i[1]][i[0]][0]。你知道吗

您的最终代码是:

import cv2
import numpy as np
import sys
import math


img = cv2.imread("images/diffc.jpeg", 0)
ci = cv2.imread("images/diffc.jpeg")

cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)



minDist = 150
param1 = 120
param2 = 37

minRadius = 120
maxRadius = 140


circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,minDist,
                          param1=param1,param2=param2,minRadius=minRadius,maxRadius=maxRadius)


if circles is None:
      print("No circles detected!")
      sys.exit(-1)


circles = np.uint16(np.around(circles))

for i in circles[0,:]:

  # draw the outer circle
  cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
  # draw the center of the circle
  cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
  print("Center of the circle: ", i[0]," ", i[1])
  # STATEMENTS THAT THROW ERROR
  print(ci[i[1]][i[0]][0]," blue")
  print(ci[i[1]][i[0]][1]," green")
  print(ci[i[1]][i[0]][2]," red")

cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

相关问题 更多 >