我正在尝试使用 OpenCV Python 从图像中提取羊牙,但是还有一些其他的东西是用牙齿提取的,我只想要牙齿。
我的密码是:
import cv2
import numpy as np
# Load the image
img = cv2.imread('4_years_1.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply a threshold to segment the teeth
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# Remove small objects from the binary image
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=3)
# Find the contours of the teeth
contours, hierarchy = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw the contours on a blank image to create a mask
mask = np.zeros_like(img)
cv2.drawContours(mask, contours, -1, (255, 255, 255), thickness=-1)
# Apply the mask to the original image
result = cv2.bitwise_and(img, mask)
# Display the result
cv2.imshow('Result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()