Длинный пост - пожалуйста, потерпите меня.
Для лучшего понимания того, какова цель и что я сделал до сих пор, я разместил код. Пожалуйста, дайте мне знать, если потребуется дополнительная информация.
У меня есть изображение (как показано) и цель состоит в том, чтобы правильно классифицировать количество положительных (синих) и отрицательных (фиолетовых) кругов. Меня не волнуют полукруги на изображении. Как показано на изображении, есть 29 кругов (исключая полукруги), в которых есть 7 положительных. Но мой код обнаруживает только 1 положительный результат. Вот что я сделал до сих пор:
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
import math
import cv2.cv as cv
# --------Read Images--------------------------
I = cv2.imread('input_image.jpg')
# -----------Apply Contrast---------------------
lab = cv2.cvtColor(I, cv2.COLOR_BGR2LAB) # Converting image to LAB Color model
l, a, b = cv2.split(lab) # Splitting the LAB image to different channels
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8)) # Applying CLAHE to L-channel
cl = clahe.apply(l)
limg = cv2.merge((cl, a, b)) # Merge the CLAHE enhanced L-channel with the a and b channel
localContrast = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR) # Converting image from LAB Color model to RGB model
print("Local Contrast shape is", localContrast.shape)
print("Local Contrast shape is", type(localContrast))
cv2.imwrite('./Output/localContrast.jpg', localContrast)
# -------------Find Circles -----------------------
input_img = cv2.imread('./Output/localContrast.jpg') # Read Contrast Image
gray_img = cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)
blur_img = cv2.medianBlur(gray_img, 7)
circles = cv2.HoughCircles(blur_img, cv.CV_HOUGH_GRADIENT, dp=1, minDist=20, param1=50, param2=30, minRadius=5,
maxRadius=36)
circles = np.uint16(np.around(circles))
no_of_circles = 0
radii = []
cx= []
cy = []
if circles is not None:
# convert the (x, y) coordinates and radius of the circles to integers
circles = np.round(circles[0, :]).astype("int")
no_of_circles = len(circles)
# loop over the (x, y) coordinates and radius of the circles
for (x,y,r) in circles:
radii.append(r)
cx.append(x)
cy.append(y)
centers = [cx, cy]
# draw the circle in the output image, then draw a rectangle
# corresponding to the center of the circle
cv2.circle(input_img, (x, y), r, (0, 0, 255), 2)
cv2.imwrite('/home/vr1019/Notebook/Output/circle_img.jpg', input_img)
print ('no of circles',no_of_circles)
Вывод показан на изображении ниже: («количество кругов», 30)
Затем я рассчитал интенсивность каждого круга, взяв верхние 10 % значения пикселя (именно так мне нужно рассчитать интенсивность). Идея взята из createCirclesMask.m
def createCircleMask(localContrast, centers, radii):
radii = np.reshape(radii, (len(radii),1))
centers = np.asarray(centers)
centers = np.transpose(centers)
xdim = localContrast.shape[0]
ydim = localContrast.shape[1]
x = np.arange(0, xdim)
y = np.arange(0, ydim)
x = np.reshape(x, (1, len(x)))
y = np.reshape(y, (1, len(y)))
[xx,yy]= np.meshgrid(y, x)
xc = centers[:,0]
xc = np.reshape(xc, (len(xc),1))
yc = centers[:,1]
yc = np.reshape(yc, (len(yc),1))
circle_intensity = []
for ii in range(len(radii)):
r_square = np.square(radii)
var1= (np.square(y-xc[ii,0]))
var2 = np.square(np.transpose(x)-yc[ii,0])
cx,cy = np.where((var1 + var2)<r_square[ii])
i1 =[]
i2 =[]
i3 =[]
npixel = cx.shape[0]
for j in range(npixel):
i1.append(localContrast[cx[j],cy[j],0]);
localContrast[cx[j],cy[j],0] = 0;
i2.append(localContrast[cx[j],cy[j],1]);
localContrast[cx[j],cy[j],1] = 0;
i3.append(localContrast[cx[j],cy[j],2]);
localContrast[cx[j],cy[j],2] = 0;
s1= sorted(i1, reverse = True)
s2=sorted(i2, reverse = True)
s3=sorted(i3, reverse = True)
# top 10 percent intensity
m1 = np.asarray(s1[0:np.int(round(abs(len(s1)*0.1)))])
m2 = np.asarray(s1[0:np.int(round(abs(len(s2)*0.1)))])
m3 = np.asarray(s1[0:np.int(round(abs(len(s3)*0.1)))])
m = np.mean((m1+m2+m3)/3)
circle_intensity.append(m)
print("The len of circle_intensty is", len(circle_intensity))
return circle_intensity
а затем построение гистограммы circle_intensity дает:
Я не знаю, что я делаю неправильно. Может ли кто-нибудь помочь мне здесь? Я искал в Интернете решение (например, pyimagesearch или stackoverflow и т. д.), но не смог найти то, что искал.