def thresholding(img_grey):
"""
This functions creates binary images using thresholding
:param img_grey: greyscale image
:return: binary image
"""
# # Global
# ret1, thresh1 = cv.threshold(img_grey, 127, 255, cv.THRESH_BINARY_INV)
# show_img(thresh1)
#
# # Adaptive Mean
# img_binary = cv.adaptiveThreshold(img_grey, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 2)
# ret2, thresh2 = cv.threshold(img_binary, 127, 255, cv.THRESH_BINARY_INV)
# show_img(thresh2)
#
# # Adaptive Gaussian
# img_binary = cv.adaptiveThreshold(img_grey, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2)
# ret3, thresh3 = cv.threshold(img_binary, 127, 255, cv.THRESH_BINARY_INV)
# show_img(thresh3)
# Otsu's thresholding after Gaussian filtering
blur = cv.GaussianBlur(img_grey, (5, 5), 0)
ret4, img_otsu = cv.threshold(blur, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
ret4, thresh4 = cv.threshold(img_otsu, 127, 255, cv.THRESH_BINARY_INV)
# show_img(thresh4)
return thresh4
python类THRESH_BINARY的实例源码
Artificial-potential-without-controller.py 文件源码
项目:Artificial-Potential-Field
作者: vampcoder
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def classify(img):
cimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img2 = cv2.medianBlur(cimg, 13)
ret, thresh1 = cv2.threshold(cimg, 100, 120, cv2.THRESH_BINARY)
t2 = copy.copy(thresh1)
x, y = thresh1.shape
arr = np.zeros((x, y, 3), np.uint8)
final_contours = []
image, contours, hierarchy = cv2.findContours(t2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#cv2.imshow('image', image)
#k = cv2.waitKey(0)
for i in range(len(contours)):
cnt = contours[i]
if cv2.contourArea(cnt) > 35000 and cv2.contourArea(cnt) < 15000:
cv2.drawContours(img, [cnt], -1, [0, 255, 255])
cv2.fillConvexPoly(arr, cnt, [255, 255, 255])
final_contours.append(cnt)
cv2.imshow('arr', arr)
k = cv2.waitKey(0)
return arr
def get_image_xy_corner(self):
"""get ?artesian coordinates from raster"""
import cv2
if not self.image_path:
return False
image_xy_corners = []
img = cv2.imread(self.image_path, cv2.IMREAD_GRAYSCALE)
imagem = (255 - img)
try:
ret, thresh = cv2.threshold(imagem, 10, 128, cv2.THRESH_BINARY)
try:
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
except Exception:
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
hierarchy = hierarchy[0]
hierarhy_contours = [[] for _ in range(len(hierarchy))]
for fry in range(len(contours)):
currentContour = contours[fry]
currentHierarchy = hierarchy[fry]
cc = []
# epsilon = 0.0005 * cv2.arcLength(contours[len(contours) - 1], True)
approx = cv2.approxPolyDP(currentContour, self.epsilon, True)
if len(approx) > 2:
for c in approx:
cc.append([c[0][0], c[0][1]])
parent_index = currentHierarchy[3]
index = fry if parent_index < 0 else parent_index
hierarhy_contours[index].append(cc)
image_xy_corners = [c for c in hierarhy_contours if len(c) > 0]
return image_xy_corners
except Exception as ex:
self.error(ex)
return image_xy_corners
def run(self, ips, snap, img, para = None):
med = cv2.ADAPTIVE_THRESH_MEAN_C if para['med']=='mean' else cv2.ADAPTIVE_THRESH_GAUSSIAN_C
mtype = cv2.THRESH_BINARY_INV if para['inv'] else cv2.THRESH_BINARY
cv2.adaptiveThreshold(snap, para['max'], med, para['inv'], para['size'], para['offset'], dst=img)
def img_sobel_binary(im, blur_sz):
# ??????????????
img_blur = cv2.GaussianBlur(im,blur_sz,0)
if len(img_blur.shape) == 3:
blur_gray = cv2.cvtColor(img_blur,cv2.COLOR_BGR2GRAY)
else:
blur_gray = img_blur
# ??Sobel????
sobelx = cv2.Sobel(blur_gray,cv2.CV_16S,1,0,ksize=3)
abs_sobelx = np.absolute(sobelx)
sobel_8u = np.uint8(abs_sobelx)
img_show_hook("Sobel??", sobel_8u)
# OTSU??????
ret, thd = cv2.threshold(sobel_8u, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
thd_abs = cv2.convertScaleAbs(thd)
bgimg = cv2.addWeighted(thd_abs, 1, 0, 0, 0)
img_show_hook("OTSU????", bgimg)
return bgimg
def img_sobel_binary(im, blur_sz):
# ??????????????
img_blur = cv2.GaussianBlur(im,blur_sz,0)
if len(img_blur.shape) == 3:
blur_gray = cv2.cvtColor(img_blur,cv2.COLOR_BGR2GRAY)
else:
blur_gray = img_blur
# ??Sobel????
sobelx = cv2.Sobel(blur_gray,cv2.CV_16S,1,0,ksize=3)
abs_sobelx = np.absolute(sobelx)
sobel_8u = np.uint8(abs_sobelx)
img_show_hook("Sobel??", sobel_8u)
# OTSU??????
ret, thd = cv2.threshold(sobel_8u, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
thd_abs = cv2.convertScaleAbs(thd)
bgimg = cv2.addWeighted(thd_abs, 1, 0, 0, 0)
img_show_hook("OTSU????", bgimg)
return bgimg
def clean_segmentation2(segments, img_size):
seg_binary = np.zeros_like(segments)
for i in xrange(segments.shape[0]):
_,sb = cv2.threshold(np.copy(segments[i,0])*255, 127, 255, cv2.THRESH_BINARY)
patches = get_patches(sb)
if len(patches)==0:
continue
sum_pdf_vals = [sum(pdf_dict[x,y] for x,y in p) for p in patches]
avg_pdf_vals = [sum(pdf_dict[x,y] for x,y in p)/p.shape[0] for p in patches]
max_sum_pdf = max(sum_pdf_vals)
for p_idx, p in enumerate(patches):
if avg_pdf_vals[p_idx] < 0.07 or sum_pdf_vals[p_idx] < max_sum_pdf:
for x,y in p:
seg_binary[i,0,x,y]=0
else:
for x,y in p:
seg_binary[i,0,x,y]=1
return seg_binary
def segment_ch4(self, segment_fn, segment_transform):
segs = np.zeros_like(self.ch4_images, dtype=np.float32)
ims = np.copy(self.ch4_images).reshape(-1, 1, self.ch4_images.shape[1],
self.ch4_images.shape[2])
ims = segment_transform(ims)
for i in xrange(self.ch4_images.shape[0]):
segs[i:i+1] = segment_fn(ims[i:i+1])
_,sb = cv2.threshold(np.copy(segs[i])*255, 127, 255, cv2.THRESH_BINARY)
patches = get_patches(sb)
sb = np.zeros_like(sb, dtype=np.uint8)
if len(patches) > 0:
patch = next(p for p in patches if p.shape[0] == max(p1.shape[0]
for p1 in patches))
for x,y in patch:
sb[x,y]=255
pca = decomposition.PCA(n_components=2)
pca.fit(patch)
mean, major = pca.mean_, pca.components_[0]
middle = sb.shape[0]/2
sb = cv2.warpAffine(sb, np.float32([[1,0,middle-mean[1]],
[0,1,middle-mean[0]]]), sb.shape)
sb = scipy.misc.imrotate(sb, np.arctan2(*major)*180/np.pi)
segs[i:i+1]=sb
self.ch4seg = segs
self.ch4counts = np.array([np.count_nonzero(s) for s in self.ch4seg]).reshape(1,-1)
def clean_segmentation(segments, img_size, thresh):
mean = segments.mean(axis=(0,1))
gaussian_params = gaussian_moments_fake(mean, normalize_height=True)
pdf = gaussian_pdf(*gaussian_params)
seg_binary = np.zeros_like(segments)
pdf_dict = np.zeros_like(mean)
for x in xrange(mean.shape[0]):
for y in xrange(mean.shape[1]):
pdf_dict[x,y] = pdf(x,y)
for i in xrange(segments.shape[0]):
_,sb = cv2.threshold(np.copy(segments[i,0])*255, 127, 255, cv2.THRESH_BINARY)
patches = get_patches(sb)
if len(patches)==0:
continue
sum_pdf_vals = [sum(pdf_dict[x,y] for x,y in p) for p in patches]
avg_pdf_vals = [sum(pdf_dict[x,y] for x,y in p)/p.shape[0] for p in patches]
max_sum_pdf = max(sum_pdf_vals)
for p_idx, p in enumerate(patches):
if avg_pdf_vals[p_idx] < 0.07 or sum_pdf_vals[p_idx] < max_sum_pdf:
for x,y in p:
seg_binary[i,0,x,y]=0
else:
for x,y in p:
seg_binary[i,0,x,y]=1
return seg_binary
def _do_filter(self, frame):
''' Process a single frame. '''
# blur to reduce noise
frame = cv2.GaussianBlur(frame, (5, 5), 0, borderType=cv2.BORDER_CONSTANT)
# threshold to find contiguous regions of "bright" pixels
# ignore all "dark" (<1/8 max) pixels
max = numpy.max(frame)
min = numpy.min(frame)
# if the frame is completely dark, then just return it
if max == min:
return frame
threshold = min + (max - min) / 8
_, frame = cv2.threshold(frame, threshold, 255, cv2.THRESH_BINARY)
# filter out single pixels and other noise
frame = cv2.erode(frame, self._element_shrink)
# restore and join nearby regions (in case one fish has a skinny middle...)
frame = cv2.dilate(frame, self._element_grow)
return frame
def checkAvailability(sift, tkp, tdes, matchimg):
"""
:param sift:
:param tkp:
:param tdes:sift feature object, template keypoints, and template descriptor
:param matchimg:
:return:
"""
qimg = cv2.imread(matchimg)
qimggray = cv2.cvtColor(qimg,cv2.COLOR_BGR2GRAY)
# kernel = np.ones((5,5), np.uint8)
# qimggray = cv2.erode(qimggray, kernel, iterations=1)
# ret,threshimg = cv2.threshold(qimggray,100,255,cv2.THRESH_BINARY)
qkp,qdes = sift.detectAndCompute(qimggray, None)
# plt.imshow(threshimg, 'gray'), plt.show()
FLANN_INDEX_KDITREE=0
index_params=dict(algorithm=FLANN_INDEX_KDITREE,tree=5)
# FLANN_INDEX_LSH = 6
# index_params = dict(algorithm=FLANN_INDEX_LSH,
# table_number=12, # 12
# key_size=20, # 20
# multi_probe_level=2) # 2
search_params = dict(checks = 50)
flann=cv2.FlannBasedMatcher(index_params,search_params)
matches=flann.knnMatch(tdes,qdes,k=2)
goodMatch=[]
for m_n in matches:
if len(m_n) != 2:
continue
m, n = m_n
if(m.distance<0.75*n.distance):
goodMatch.append(m)
MIN_MATCH_COUNT = 30
if (len(goodMatch) >= MIN_MATCH_COUNT):
tp = []
qp = []
for m in goodMatch:
tp.append(tkp[m.queryIdx].pt)
qp.append(qkp[m.trainIdx].pt)
tp, qp = np.float32((tp, qp))
H, status = cv2.findHomography(tp, qp, cv2.RANSAC, 3.0)
h = timg.shape[0]
w = timg.shape[1]
trainBorder = np.float32([[[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]])
queryBorder = cv2.perspectiveTransform(trainBorder, H)
cv2.polylines(qimg, [np.int32(queryBorder)], True, (0, 255, 0), 5)
cv2.imshow('result', qimg)
plt.imshow(qimg, 'gray'), plt.show()
return True
else:
print "Not Enough match found- %d/%d" % (len(goodMatch), MIN_MATCH_COUNT)
return False
# cv2.imshow('result', qimg)
# if cv2.waitKey(10) == ord('q'):
# cv2.destroyAllWindows()
def get_speed(frame):
"""
:param frame: Captured image
:return: Speed
"""
# Disable speed detection
return 0
speed = frame[settings.IMAGE_SPEED_Y[0]:settings.IMAGE_SPEED_Y[1], settings.IMAGE_SPEED_X[0]:settings.IMAGE_SPEED_X[1]]
speed_gray = cv2.cvtColor(speed, cv2.COLOR_BGR2GRAY)
# Zoom
rows, cols = speed_gray.shape[:2]
M = np.float32([[2, 0, 0], [0, 2, 0]])
speed_zoom = cv2.warpAffine(speed_gray, M, (cols * 2, rows * 2))
_, speed_threshold = cv2.threshold(speed_zoom, 210, 255, cv2.THRESH_BINARY)
to_detect = speed_threshold[:, 26:]
#cv2.imshow('speed', to_detect)
to_detect = cv2.resize(to_detect, (20, 20))
to_detect = to_detect.reshape((1, 400))
to_detect = np.float32(to_detect)
_, results, _, _ = model.findNearest(to_detect, k=1)
return int((results[0][0]))
def logoDetect(img,imgo):
'''???????????????'''
imglogo=imgo.copy()
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img=cv2.resize(img,(2*img.shape[1],2*img.shape[0]),interpolation=cv2.INTER_CUBIC)
#img=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,-3)
ret,img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
#img=cv2.Sobel(img, cv2.CV_8U, 1, 0, ksize = 9)
img=cv2.Canny(img,100,200)
element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
img = cv2.dilate(img, element2,iterations = 1)
img = cv2.erode(img, element1, iterations = 3)
img = cv2.dilate(img, element2,iterations = 3)
#????
im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
tema=0
result=[]
for con in contours:
x,y,w,h=cv2.boundingRect(con)
area=w*h
ratio=max(w/h,h/w)
if area>300 and area<20000 and ratio<2:
if area>tema:
tema=area
result=[x,y,w,h]
ratio2=ratio
#?????????????????,??????????
logo2_X=[int(result[0]/2+plate[0]-3),int(result[0]/2+plate[0]+result[2]/2+3)]
logo2_Y=[int(result[1]/2+max(0,plate[1]-plate[3]*3.0)-3),int(result[1]/2+max(0,plate[1]-plate[3]*3.0)+result[3]/2)+3]
cv2.rectangle(img,(result[0],result[1]),(result[0]+result[2],result[1]+result[3]),(255,0,0),2)
cv2.rectangle(imgo,(logo2_X[0],logo2_Y[0]),(logo2_X[1],logo2_Y[1]),(0,0,255),2)
print tema,ratio2,result
logo2=imglogo[logo2_Y[0]:logo2_Y[1],logo2_X[0]:logo2_X[1]]
cv2.imwrite('./logo2.jpg',logo2)
return img
def extractPlantsArea(self, arg_mode=0,arg_INV= False, b_threshold=80, a_threshold=80):
zeros = np.zeros(self.image.shape[:2], dtype = "uint8")
imgLAB = cv2.cvtColor(self.image, self.colorSpace)
(L, A, B) = cv2.split(imgLAB)
cv2.imwrite('Debug/imgB.jpg',B)
cv2.imwrite('Debug/imgA.jpg',A)
#(T_weeds_b, thresh_weeds_b) = cv2.threshold(B, b_threshold, 255, cv2.THRESH_BINARY)
#(T_weeds_a, thresh_weeds_a) = cv2.threshold(A, a_threshold, 255, cv2.THRESH_BINARY)
if arg_mode==0:
thresh_weeds_a= imgProcess_tool.binarialization(A,0,arg_INV, a_threshold)
thresh_weeds_b= imgProcess_tool.binarialization(B,0,arg_INV, b_threshold)
elif arg_mode==1:
thresh_weeds_b= imgProcess_tool.binarialization(B, 1, arg_INV)
thresh_weeds_a= imgProcess_tool.binarialization(A, 1, arg_INV)
elif arg_mode==2:
thresh_weeds_b= imgProcess_tool.binarialization(B, 2, arg_INV)
thresh_weeds_a= imgProcess_tool.binarialization(A, 2, arg_INV)
cv2.imwrite('Debug/imgB_thr.jpg',thresh_weeds_b)
cv2.imwrite('Debug/imgA_thr.jpg',thresh_weeds_a)
imgRGB = cv2.merge([zeros, thresh_weeds_b, thresh_weeds_a])
return thresh_weeds_a, thresh_weeds_b
def get_contour(self, arg_frame, arg_export_index, arg_export_path, arg_export_filename, arg_binaryMethod):
# Otsu's thresholding after Gaussian filtering
tmp = cv2.cvtColor(arg_frame, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(tmp,(5,5),0)
if arg_binaryMethod== 0:
ret, thresholdedImg= cv2.threshold(blur.copy() , self.threshold_graylevel, 255 , 0)
elif arg_binaryMethod == 1:
ret,thresholdedImg = cv2.threshold(blur.copy(),0 ,255 ,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
elif arg_binaryMethod== 2:
thresholdedImg = cv2.adaptiveThreshold(blur.copy(),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,0)
result = cv2.cvtColor(thresholdedImg, cv2.COLOR_GRAY2RGB)
ctrs, hier = cv2.findContours(thresholdedImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
ctrs = filter(lambda x : cv2.contourArea(x) > self.threshold_size , ctrs)
rects = [[cv2.boundingRect(ctr) , ctr] for ctr in ctrs]
for rect , cntr in rects:
cv2.drawContours(result, [cntr], 0, (0, 128, 255), 3)
if arg_export_index:
cv2.imwrite(arg_export_path+ arg_export_filename+'.jpg', result)
print "Get Contour success"
return result
def binary_morph(img, thresh=50, min_size=None, mask_only=True):
if min_size is None: # default to 10% of largest image dimension
min_size = float(max(img.shape)) * .1
if len(img.shape) == 3: # flatten if RGB image
img = np.mean(img, 2).astype(np.uint8)
# Apply binary threshold and erode
ret, thresh_im = cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY)
# Connected component labelling
n, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh_im)
mask = np.zeros_like(labels)
# Loop through areas in order of size
areas = [s[4] for s in stats]
sorted_idx = np.argsort(areas)
for lidx, cc in zip(sorted_idx, [areas[s] for s in sorted_idx][:-1]):
if cc > min_size:
mask[labels == lidx] = 1
if mask_only:
return mask * 255
return np.dstack([img * mask] * 3).astype(np.uint8)
def find_lines(img, acc_threshold=0.25, should_erode=True):
if len(img.shape) == 3 and img.shape[2] == 3: # if it's color
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img = cv2.GaussianBlur(img, (11, 11), 0)
img = cv2.adaptiveThreshold(
img,
255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
5,
2)
img = cv2.bitwise_not(img)
# thresh = 127
# edges = cv2.threshold(img, thresh, 255, cv2.THRESH_BINARY)[1]
# edges = cv2.Canny(blur, 500, 500, apertureSize=3)
if should_erode:
element = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))
img = cv2.erode(img, element)
theta = np.pi/2000
angle_threshold = 2
horizontal = cv2.HoughLines(
img,
1,
theta,
int(acc_threshold * img.shape[1]),
min_theta=np.radians(90 - angle_threshold),
max_theta=np.radians(90 + angle_threshold))
vertical = cv2.HoughLines(
img,
1,
theta,
int(acc_threshold * img.shape[0]),
min_theta=np.radians(-angle_threshold),
max_theta=np.radians(angle_threshold),
)
horizontal = list(horizontal) if horizontal is not None else []
vertical = list(vertical) if vertical is not None else []
horizontal = [line[0] for line in horizontal]
vertical = [line[0] for line in vertical]
horizontal = np.asarray(horizontal)
vertical = np.asarray(vertical)
return horizontal, vertical
def remove_noise_and_smooth(file_name):
logging.info('Removing noise and smoothening image')
img = cv2.imread(file_name, 0)
filtered = cv2.adaptiveThreshold(img.astype(np.uint8), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 41, 3)
kernel = np.ones((1, 1), np.uint8)
opening = cv2.morphologyEx(filtered, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)
img = image_smoothening(img)
or_image = cv2.bitwise_or(img, closing)
return or_image
def convert_and_count(target, ext):
for root, dirs, files in os.walktarget):
for f in files:
fname, fext = os.path.splitext(f)
if fext == ext:
img = cv2.imread(os.path.join(root, f), 0)
blur = cv2.GaussianBlur(img, (5, 5), 0)
ret, imgb = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imwrite(os.path.join(root, fname + ".bin.png"), imgb)
cnt = 0
for val in imgb.flat:
if val == 0:
cnt += 1
ratio = cnt / img.size
msg = "%s:\t%.5f" % (f, ratio)
print(msg)