I hope you are doing well. I want to count the corner points in the image of a given color. Like blue colour has two shapes how can i find and count that corner points
I have used the following code But It find out the corner of shape not color
import cv2
import numpy as np
import matplotlib.pyplot as plt
def cornerpoint(img):
img = cv2.imread(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,5,3,0.04)
ret, dst = cv2.threshold(dst,0.1*dst.max(),255,0)
dst = np.uint8(dst)
ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
criteria = (cv2.TERM_CRITERIA_EPS cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),(-1,-1),criteria)
for i in range(1, len(corners)):
print(corners[i])
img[dst>0.1*dst.max()]=[0,0,0]
plt.imshow(img)
cornerpoint('/content/shapes.png')
How can I proceed to count the corner points in the image of a given color?
CodePudding user response:
In response to questions raised in the comments, here is one way to get the list of unique colors ignoring the anti-aliasing of the colors.
(You could also use morphology to thin your colored lines to remove the anti-aliased pixels)
- Read the input
- Reshape to 1D image of 3 channels
- Use np.unique to get the colors and counts
- Zip the colors and counts
- Put the zip into a list
- Sort the zipped list on count in reverse order
- Print only those colors that have counts above some threshold.
- (Note: other filters could be used to check colors against each other to be sure not too close or to remove colors near the background color. Etc)
Input:
import cv2
import numpy as np
# read image
img = cv2.imread('colored_polygons.png')
# reshape img to 1 column of 3 colors
# -1 means figure out how big it needs to be for that dimension
img2 = img.reshape(-1,3)
# get the unique colors
colors, counts = np.unique(img2, return_counts=True, axis=0)
# zip colors, counts
unique = zip(colors,counts)
# make list of color, count
cc_list = []
for color, count in unique:
cc_list.append((color, count))
# function to define key as second element (count)
def takeSecond(elem):
return elem[1]
# sort cc_list on counts
cc_list.sort(key=takeSecond, reverse=True)
# print sorted list and threshold on count
index = 0
for item in cc_list:
color = item[0]
count = item[1]
if count > 5000:
index = 1
print("index:", index, "count:", count, "color:", color)
List of Top Unique Colors:
index: 1 count: 428771 color: [255 255 255]
index: 2 count: 15735 color: [0 0 0]
index: 3 count: 9760 color: [ 14 127 0]
index: 4 count: 9160 color: [255 38 0]
index: 5 count: 8893 color: [ 0 0 255]