我正在使用 opencv 从该图像中提取中间的大骨头,但我似乎无法锻炼如何做到这一点
如您所见,所有 3 根骨头都显示出来,但我只想要中间的骨头 这是代码
b = cv.imread('content/B.tif', cv.IMREAD_GRAYSCALE)
plt.figure(figsize=(5,5))
plt.imshow(b, cmap='gray')
plt.axis('off')
plt.show()
_, binary_b = cv.threshold(b, 200, 255, cv.THRESH_BINARY)
b_e = cv.erode(binary_b, np.ones((1,1), dtype=np.uint8))
b_d = cv.dilate(b_e, np.ones((5,5), dtype=np.uint8),iterations = 3)
xor = cv.bitwise_and(b_d,b)
plt.figure(figsize=(5,5))
plt.imshow(xor, cmap='gray')
plt.axis('off')
plt.show()
有人可以帮忙吗?
您需要继续对不同的图像执行此操作还是仅在这种情况下执行此操作?
您可以使用边缘检测器计算边界并删除右侧第二个边界。
我尝试使用轮廓找到中心骨骼,因为它是最大的。请参阅下面的代码以及注释中的解释。希望这有帮助。
import cv2
import numpy as np
#Read image and convert to gray scale
image = cv2.imread("bone.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresholded_image = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
#Dilate image to close gaps
#Erode image to remove additional edges created using dilation
#number of iteration found by trial and error
kernel = np.ones((5,5),np.uint8)
thresholded_image = cv2.dilate(thresholded_image, kernel,iterations=5)
thresholded_image = cv2.erode(thresholded_image, kernel,iterations=5)
#get the contour of dilate eroded image
contours, hierarchy = cv2.findContours(thresholded_image, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
#Since center bone is largest
#Find contour with max length
max_length=0
max_length_ctr=None
for ctr in contours:
x,y,w,h = cv2.boundingRect(ctr)
if h > max_length:
max_length = h
max_length_ctr = ctr
#Use the found contour to create mask and get the bone
if max_length_ctr is not None:
big_bone_mask = np.zeros_like(thresholded_image)
cv2.drawContours(big_bone_mask, [max_length_ctr], -1, (255, 255, 255), -1)
cv2.imwrite("big_bone_mask.png",big_bone_mask)
# Get the graph from original image from the mask
bone_image = cv2.bitwise_and(image, image, mask=big_bone_mask)
cv2.imwrite("bone_image.png", bone_image)