我是OpenCV和Python的新手。我已经能够找到Contours并在轮廓上绘制boundingRect并将其另存为新图像。我遇到了一个问题,似乎该程序正在保存2张图像,因为找到的轮廓中有重复的图像。我被困在这一部分中,如何避免重复?
代码如下:
img = cv2.imread('2.bmp')
img_2 = cv2.imread('2.bmp')
input_img = cv2.addWeighted(img, 0.55, img_2, 0.6, 0)
retval, threshold = cv2.threshold(input_img, 158, 255, cv2.THRESH_BINARY)
threshold = cv2.cvtColor(threshold, cv2.COLOR_BGR2GRAY)
retval2, threshold2 = cv2.threshold(threshold, 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
blur2 = cv2.medianBlur(threshold2,5)
canny = cv2.Canny(blur2, 100,200)
im2, contours, hierarchy = cv2.findContours(canny,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
maxsize = 0
best = 0
count = 0
limit_area = 1000
number_name = 0
x = 0
y = 0
w = 0
h = 0
nuclei = []
for cnt in contours:
if cv2.contourArea(cnt) >= limit_area:
print(cv2.contourArea(cnt))
nuclei.append(cnt)
print(count)
x, y, w, h = cv2.boundingRect(cnt)
roi = blur2[y:y+h, x:x+w]
outfile = '%d.jpg' % number_name
cv2.imwrite(outfile, roi)
number_name += 1
cnt+=1
count += 1
cv2.drawContours(blur2, nuclei, -1, (0,0,255), 2)
cv2.rectangle(blur2, (x, y), (x+w, y+h), (0,255,0), 7)
这是我一直在尝试使用此程序的图像:
答案 0 :(得分:0)
我认为此更改应该为您完成。
im2, contours, hierarchy = cv2.findContours(canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
此外,您应该对灰色图像而不是彩色图像进行阈值处理。以下代码行将帮助您获得更好的结果:
img = cv2.imread('nuclei.png',cv2.IMREAD_GRAYSCALE)
retval, threshold = cv2.threshold(255-img, 100,255, cv2.THRESH_BINARY)