Reputation: 131
I am trying to locate three objects in my image and crop the sherd out. Any way that I can detect the edges better? This is the code I use to detect objects.
def getEdgedImg(img):
kernel = np.ones((3,3), np.uint8)
eroded = cv2.erode(img, kernel)
blur = cv2.medianBlur(eroded, 3)
med_val = np.median(eroded)
lower = int(max(0, 0.5*med_val))
upper = int(min(255, 1.3*med_val))
edged = cv2.Canny(blur, lower, upper)
return edged
edged = getEdgedImg(img)
_, contours= cv2.findContours(edged ,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE
for cnt in contours:
if cv2.contourArea(colour_cnts[i]) > 400:
x, y, w, h = cv2.boundingRect(colour_cnts[i])
cv2.rectangle(img2, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('hi', img)
cv2.waitKey(0)
I am currently doing image processing in my raw images. I have been looking for a few methods to improve the results but still, it doesn't work very well for some photos.
edge detected:
Upvotes: 1
Views: 237
Reputation: 614
Had a shot at it, but as expected the weak background contrast is giving trouble, as does the directed lighting. Just checking the stone right now, but the script should give you the tools to find the two reference cards as well. If you want to show the intermediate images, see the comments in the script.
Do you have the original image in another format then JPG by chance ? The color compression in the file is really not helping with extraction.
import cv2
# get image
img = cv2.imread("<YouPathHere>")
# extract stone shadow in RGB
chB, chG, chR = cv2.split(img)
threshShadow = 48
imgChanneldiff = chR-chB
imgshadow = cv2.threshold(imgChanneldiff,threshShadow,255,cv2.THRESH_BINARY)[1]
#cv2.namedWindow("imgshadow", cv2.WINDOW_NORMAL)
#cv2.imshow("imgshadow", imgshadow)
# extract stone together with shadow in HSV
imgHSV = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
threshHue = 10
chH, chS, chV = cv2.split(imgHSV)
imgbin = cv2.threshold(chH,threshHue,255,cv2.THRESH_BINARY)[1]
#cv2.namedWindow("imgbin", cv2.WINDOW_NORMAL)
#cv2.imshow("imgbin", imgbin)
imgResultMask = imgbin - imgshadow
MorphKernelSize = 25;
imgResultMask = cv2.erode(imgResultMask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, [MorphKernelSize,MorphKernelSize]))
imgResultMask = cv2.dilate(imgResultMask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, [MorphKernelSize,MorphKernelSize]))
cv2.namedWindow("imgResultMask", cv2.WINDOW_NORMAL)
cv2.imshow("imgResultMask", imgResultMask)
contours = cv2.findContours(imgResultMask,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[0]
cv2.drawContours(img, contours, -1, (255,125,0), 3)
for c in contours:
cv2.rectangle(img, cv2.boundingRect(c), (0,125,255))
cv2.namedWindow("img", cv2.WINDOW_NORMAL)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Upvotes: 2