Uzair
Uzair

Reputation: 71

Detecting angles in a piechart using OpenCV technique

I am trying to detect angles in a piechat Image using OpenCV. I detect the lines using HoughlinesP and trying to find angles between lines but it is not showing right angle and if there is any straight line (like 180 degree) in pie chart, there will an issue.

I tried another technique using findContours. It will give me a boundary area of a piechart, but I stuck there, I don't know what should be next step.

Edited Here is the Image as a sample:

PieChat

This is a result of Contours

Any help, Any path you given will be appreciated. Thanks in advance.

Upvotes: 0

Views: 667

Answers (1)

Ian Chu
Ian Chu

Reputation: 3143

I'm thresholding off of the color values of the slices and counting the number of pixels in the slice. I'm converting the pixel count to percentages and then the percentages to angles.

enter image description here

The output I get is:

[54.4, 18.3, 27.3]

[195.84, 65.88, 98.28]

import cv2
import numpy as np

# get pixel value under mouse
def clicky(event, x, y, flags, params):
    if event == cv2.EVENT_LBUTTONUP:
        global h;
        print(h[y][x]);

# load image
img = cv2.imread("pie.jfif");

# resize
scale = 0.5;
h, w = img.shape[:2];
h = int(h*scale);
w = int(w*scale);
img = cv2.resize(img, (w,h));

# hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV);
h,s,v = cv2.split(hsv);
h = cv2.medianBlur(h, 5);

# find values
cv2.namedWindow("Hue");
cv2.setMouseCallback("Hue", clicky);
while True:
    cv2.imshow("Hue", h);
    if cv2.waitKey(1) == ord('q'):
        break;

# threshold (102, 60, 14)
slices = [];
ranges = [102, 60, 14];
for r in ranges:
    mask = cv2.inRange(h, r-1, r+1);
    slices.append(np.sum(mask == 255));

# convert slices to percentages
percents = [];
total = sum(slices);
for s in slices:
    percent = (s / total) * 100;
    percents.append(round(percent, 1));
print(percents);

# convert to angles
angles = [];
total = 360;
for p in percents:
    angles.append(p * total / 100);
print(angles);

Press 'q' on the image to move past the color-finding section of the code.

Upvotes: 1

Related Questions