import os
import cv2
def threshold(img, thresh=128, maxval=255, type=cv2.THRESH_BINARY):
if len(img.shape) == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshed = cv2.threshold(img, thresh, maxval, type)[1]
return threshed
import cv2
def threshold(img, thresh=128, maxval=255, type=cv2.THRESH_BINARY):
if len(img.shape) == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshed = cv2.threshold(img, thresh, maxval, type)[1]
return threshed
def find_contours(img):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
morphed = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imshow("morphed",morphed)
cv2.waitKey(0)
contours = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(contours)):
#cv2.drawContours(immask,[contours[i]],-1,(x+np.random.randint(0, 30),x+np.random.randint(0, 30),x+np.random.randint(0, 30)),cv2.FILLED)
cv2.drawContours(morphed,[contours[i]],-1,(0,0,0),cv2.FILLED)
import pdb
pdb.set_trace()
cv2.imshow("morphed2",morphed)
cv2.waitKey(0)
return contours[-2]
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
morphed = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
cv2.imshow("morphed",morphed)
cv2.waitKey(0)
contours = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(contours)):
#cv2.drawContours(immask,[contours[i]],-1,(x+np.random.randint(0, 30),x+np.random.randint(0, 30),x+np.random.randint(0, 30)),cv2.FILLED)
cv2.drawContours(morphed,[contours[i]],-1,(0,0,0),cv2.FILLED)
import pdb
pdb.set_trace()
cv2.imshow("morphed2",morphed)
cv2.waitKey(0)
return contours[-2]
def mask_from_contours(ref_img, contours):
mask = numpy.zeros(ref_img.shape, numpy.uint8)
mask = cv2.drawContours(mask, contours, -1, (255,255,255), -1)
return cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
mask = numpy.zeros(ref_img.shape, numpy.uint8)
mask = cv2.drawContours(mask, contours, -1, (255,255,255), -1)
return cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
def dilate_mask(mask, kernel_size=11):
kernel = numpy.ones((kernel_size,kernel_size), numpy.uint8)
dilated = cv2.dilate(mask, kernel, iterations=1)
return dilated
img=cv2.imread("1110_3_1_X_537_Y_1700_qly_100_fail_13d17h46m24s.bmp",0)
imgray = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
img=imgray
thresh=threshold(imgray)
threshcontours=find_contours(thresh)
mask= mask_from_contours(img, contours)
mask= dilate_mask(mask, 50)
crop= cv2.bitwise_or(img, img, mask=mask)
kernel = numpy.ones((kernel_size,kernel_size), numpy.uint8)
dilated = cv2.dilate(mask, kernel, iterations=1)
return dilated
img=cv2.imread("1110_3_1_X_537_Y_1700_qly_100_fail_13d17h46m24s.bmp",0)
imgray = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
img=imgray
thresh=threshold(imgray)
threshcontours=find_contours(thresh)
mask= mask_from_contours(img, contours)
mask= dilate_mask(mask, 50)
crop= cv2.bitwise_or(img, img, mask=mask)