def tresholdify(self, pic):
self.log.info("applying threshold filter")
pic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)
pic = cv2.GaussianBlur(pic, (5, 5), 0)
pic = cv2.adaptiveThreshold(pic, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
return pic
python类adaptiveThreshold()的实例源码
def detect(self, image, mask = None):
b,g,r = cv2.split(image)
difference = cv2.subtract(r, b)
difference = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# ADAPTIVE_THRESH_GAUSSIAN_C or ADAPTIVE_THRESH_MEAN_C
return cv2.adaptiveThreshold(difference, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, Configuration.adaptive_block_size, Configuration.adaptive_threshold)
def binarize(img=get_sample_image()):
thresh = cv2.adaptiveThreshold(img, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 4)
return thresh
def binarialization(arg_frame, arg_binaryMethod, arg_thresholdValue= 100):
if len(arg_frame.shape)==3:
tmp = cv2.cvtColor(arg_frame, cv2.COLOR_RGB2GRAY)
else:
tmp= arg_frame.copy()
# Otsu's thresholding after Gaussian filtering
blur = cv2.GaussianBlur(tmp,(5,5),0)
if arg_binaryMethod== 0:
ret, thresholdedImg= cv2.threshold(blur.copy() , arg_thresholdValue, 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)
return thresholdedImg
def adaptive_binarize_py(x, block_size=5, C=33.8):
"Works like an edge detector."
# ADAPTIVE_THRESH_GAUSSIAN_C, ADAPTIVE_THRESH_MEAN_C
# THRESH_BINARY, THRESH_BINARY_INV
import cv2
ret_imgs = opencv_wrapper(x, cv2.adaptiveThreshold, [255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, block_size, C])
return ret_imgs
def threshold_image_for_tape(image):
"""
Thresholds image for reflective tape with light shined on it. This means it
looks for pixels that are almost white, makes them white, and makes
everything else black.
Parameters:
:param: `image` - the source image to threshold from
"""
orig_image = numpy.copy(image)
# print orig_image.size
orig_image = cv2.medianBlur(orig_image, 3)
# orig_image[orig_image > 100] = 255
# return orig_image[orig_image > 100]
height, width = orig_image.shape[0], orig_image.shape[1]
eight_bit_image = numpy.zeros((height, width, 1), numpy.uint8)
cv2.inRange(orig_image,
(B_RANGE[0], G_RANGE[0], R_RANGE[0], 0),
(B_RANGE[1], G_RANGE[1], R_RANGE[1], 100),
eight_bit_image)
# # eight_bit_image = cv2.adaptiveThreshold(orig_image,
# # 255,
# # cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
# # cv2.THRESH_BINARY,
# # 8,
# # 0)
# cv2.medianBlur(eight_bit_image, 9)
return eight_bit_image
def th2(self,img):
# ?????
# ????
# median = cv2.medianBlur(thresh,3)
# img_blur = cv2.GaussianBlur(img_gray, (m_blurBlock,m_blurBlock), 0)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 19)
return thresh
# ?????
def __cv_adaptivethreshold(src, max_value, adaptive_method, threshold_type, block_size, c):
"""Applies an adaptive threshold to an array.
Args:
src: A gray scale numpy.ndarray.
max_value: Value to assign to pixels that match the condition.
adaptive_method: Adaptive threshold method to use. (opencv enum)
threshold_type: Type of threshold to use. (opencv enum)
block_size: Size of a pixel area that is used to calculate a threshold.(number)
c: Constant to subtract from the mean.(number)
Returns:
A black and white numpy.ndarray.
"""
return cv2.adaptiveThreshold(src, max_value, adaptive_method, threshold_type,
(int)(block_size + 0.5), c)
def __cv_adaptivethreshold(src, max_value, adaptive_method, threshold_type, block_size, c):
"""Applies an adaptive threshold to an array.
Args:
src: A gray scale numpy.ndarray.
max_value: Value to assign to pixels that match the condition.
adaptive_method: Adaptive threshold method to use. (opencv enum)
threshold_type: Type of threshold to use. (opencv enum)
block_size: Size of a pixel area that is used to calculate a threshold.(number)
c: Constant to subtract from the mean.(number)
Returns:
A black and white numpy.ndarray.
"""
return cv2.adaptiveThreshold(src, max_value, adaptive_method, threshold_type,
(int)(block_size + 0.5), c)
def adaptiveThresholding(gray=None, neighbor=5, blur=False, k_size=3):
if(blur):
gray = cv2.GaussianBlur(gray, (k_size, k_size), 0)
return cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, neighbor, 1)
def getAdaptiveThreshold(self, image):
return cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C ,\
cv2.THRESH_BINARY,21,0)
def _clean_image(self) -> None:
self._img = cv2.medianBlur(self._img, ksize=3)
self._img = cv2.adaptiveThreshold(self._img, maxValue=255, adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
thresholdType=cv2.THRESH_BINARY, blockSize=11, C=2)
self.intermediate_images.append(NamedImage(self._img.copy(), 'Clean Image'))
def subtract_back(self,frm):
#dst=self.__back__-self.__foreground__
temp=np.zeros((600,800),np.uint8)
self.__foreground__=cv2.blur(self.__foreground__,(3,3))
dst=cv2.absdiff(self.__back__,self.__foreground__)
#dst=cv2.adaptiveThreshold(dst,255,cv.CV_THRESH_BINARY,cv.CV_ADAPTIVE_THRESH_GAUSSIAN_C,5,10)
val,dst=cv2.threshold(dst,0,255,cv.CV_THRESH_BINARY+cv.CV_THRESH_OTSU)
fg=cv2.erode(dst,None,iterations=1)
bg=cv2.dilate(dst,None,iterations=4)
_,bg=cv2.threshold(bg,1,128,1)
mark=cv2.add(fg,bg)
mark32=np.int32(mark)
#dst.copy(temp)
#seq=cv.FindContours(cv.fromarray(dst),self.mem,cv.CV_RETR_EXTERNAL,cv.CV_CHAIN_APPROX_SIMPLE)
#cntr,h=cv2.findContours(dst,cv.CV_RETR_EXTERNAL,cv.CV_CHAIN_APPROX_SIMPLE)
#print cntr,h
#cv.DrawContours(cv.fromarray(temp),seq,(255,255,255),(255,255,255),1,cv.CV_FILLED)
cv2.watershed(frm, mark32)
self.final_mask=cv2.convertScaleAbs(mark32)
#print temp
#--outputs---
#cv2.imshow("subtraction",fg)
#cv2.imshow("thres",dst)
#cv2.imshow("thres1",bg)
#cv2.imshow("mark",mark)
#cv2.imshow("final",self.final_mask)
def __cv_adaptivethreshold(src, max_value, adaptive_method, threshold_type, block_size, c):
"""Applies an adaptive threshold to an array.
Args:
src: A gray scale numpy.ndarray.
max_value: Value to assign to pixels that match the condition.
adaptive_method: Adaptive threshold method to use. (opencv enum)
threshold_type: Type of threshold to use. (opencv enum)
block_size: Size of a pixel area that is used to calculate a threshold.(number)
c: Constant to subtract from the mean.(number)
Returns:
A black and white numpy.ndarray.
"""
return cv2.adaptiveThreshold(src, max_value, adaptive_method, threshold_type,
(int)(block_size + 0.5), c)
def render(self,frame):
return cv2.medianBlur(cv2.adaptiveThreshold(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,27,3),5)
def preprocess(self,img):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),5 )
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,1)
return thresh
def show_em(self):
"""Displays the EM events (grayscale ATIS events)"""
frame_length = 24e3
t_max = self.data.ts[-1]
frame_start = self.data[0].ts
frame_end = self.data[0].ts + frame_length
max_val = 1.16e5
min_val = 1.74e3
val_range = max_val - min_val
thr = np.rec.array(None, dtype=[('valid', np.bool_), ('low', np.uint64), ('high', np.uint64)], shape=(self.height, self.width))
thr.valid.fill(False)
thr.low.fill(frame_start)
thr.high.fill(0)
def show_em_frame(frame_data):
"""Prepare and show a single frame of em data to be shown"""
for datum in np.nditer(frame_data):
ts_val = datum['ts'].item(0)
thr_data = thr[datum['y'].item(0), datum['x'].item(0)]
if datum['p'].item(0) == 0:
thr_data.valid = 1
thr_data.low = ts_val
elif thr_data.valid == 1:
thr_data.valid = 0
thr_data.high = ts_val - thr_data.low
img = 255 * (1 - (thr.high - min_val) / (val_range))
#thr_h = cv2.adaptiveThreshold(thr_h, 255,
#cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 0)
img = np.piecewise(img, [img <= 0, (img > 0) & (img < 255), img >= 255], [0, lambda x: x, 255])
img = img.astype('uint8')
cv2.imshow('img', img)
cv2.waitKey(1)
while frame_start < t_max:
#with timer.Timer() as em_playback_timer:
frame_data = self.data[(self.data.ts >= frame_start) & (self.data.ts < frame_end)]
show_em_frame(frame_data)
frame_start = frame_end + 1
frame_end += frame_length + 1
#print 'showing em frame took %s seconds' %em_playback_timer.secs
cv2.destroyAllWindows()
return
def find_contours(img):
'''
:param img: (numpy array)
:return: all possible rectangles (contours)
'''
img_blurred = cv2.GaussianBlur(img, (5, 5), 1) # remove noise
img_gray = cv2.cvtColor(img_blurred, cv2.COLOR_BGR2GRAY) # greyscale image
# cv2.imshow('', img_gray)
# cv2.waitKey(0)
# Apply Sobel filter to find the vertical edges
# Find vertical lines. Car plates have high density of vertical lines
img_sobel_x = cv2.Sobel(img_gray, cv2.CV_8UC1, dx=1, dy=0, ksize=3, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT)
# cv2.imshow('img_sobel', img_sobel_x)
# Apply optimal threshold by using Oslu algorithm
retval, img_threshold = cv2.threshold(img_sobel_x, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
# cv2.imshow('s', img_threshold)
# cv2.waitKey(0)
# TODO: Try to apply AdaptiveThresh
# Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
# gaus_threshold = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 115, 1)
# cv2.imshow('or', img)
# cv2.imshow('gaus', gaus_threshold)
# cv2.waitKey(0)
# Define a stuctural element as rectangular of size 17x3 (we'll use it during the morphological cleaning)
element = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(17, 3))
# And use this structural element in a close morphological operation
morph_img_threshold = deepcopy(img_threshold)
cv2.morphologyEx(src=img_threshold, op=cv2.MORPH_CLOSE, kernel=element, dst=morph_img_threshold)
# cv2.dilate(img_threshold, kernel=np.ones((1,1), np.uint8), dst=img_threshold, iterations=1)
# cv2.imshow('Normal Threshold', img_threshold)
# cv2.imshow('Morphological Threshold based on rect. mask', morph_img_threshold)
# cv2.waitKey(0)
# Find contours that contain possible plates (in hierarchical relationship)
contours, hierarchy = cv2.findContours(morph_img_threshold,
mode=cv2.RETR_EXTERNAL, # retrieve the external contours
method=cv2.CHAIN_APPROX_NONE) # all pixels of each contour
plot_intermediate_steps = False
if plot_intermediate_steps:
plot(plt, 321, img, "Original image")
plot(plt, 322, img_blurred, "Blurred image")
plot(plt, 323, img_gray, "Grayscale image", cmap='gray')
plot(plt, 324, img_sobel_x, "Sobel")
plot(plt, 325, img_threshold, "Threshold image")
# plot(plt, 326, morph_img_threshold, "After Morphological filter")
plt.tight_layout()
plt.show()
return contours
Artificial-potential-without-controller.py 文件源码
项目:Artificial-Potential-Field
作者: vampcoder
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def find_goal(frame):
# converting to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
#show_image(hsv)
lower_blue = np.array([113, 40, 29])
upper_blue = np.array([123, 180, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
#show_image(mask)
result = cv2.bitwise_and(frame, frame, mask=mask)
#show_image(result)
blur = cv2.blur(result, (5, 5))
bw = cv2.cvtColor(blur, cv2.COLOR_HSV2BGR)
bw2 = cv2.cvtColor(bw, cv2.COLOR_BGR2GRAY)
ret, th3 = cv2.threshold(bw2, 30, 255, cv2.THRESH_BINARY)
# th3 = cv2.adaptiveThreshold(bw2,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
# cv2.THRESH_BINARY,11,2)
edges = cv2.Canny(th3, 100, 200)
th4 = copy.copy(th3)
perimeter = 0
j = 0
image, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# print len(contours)
# if(len(contours) > 5):
# continue
cnt = np.array([])
for i in range(len(contours)):
if (perimeter < cv2.contourArea(contours[i])):
perimeter = cv2.contourArea(contours[i])
j = i;
cnt = contours[j]
if (len(cnt) == 0):
return (-1, -1)
cv2.drawContours(frame, cnt, -1, (0, 255, 0), 3)
x = 0
y = 0
#print 'find goal'
#print len(cnt), j
#print cnt
for i in range(len(cnt)):
x = x + cnt[i][0][0]
y = y + cnt[i][0][1]
x = x/len(cnt)
y = y/len(cnt)
#print x, y
x = int(x)
y = int(y)
cv2.circle(frame, (x, y), 5, (255, 0, 255), -1)
#cv2.imshow('image', frame)
#k = cv2.waitKey(0)
return (int(x), int(y))
Artificial-potential-controller.py 文件源码
项目:Artificial-Potential-Field
作者: vampcoder
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def find_goal(img):
# converting to HSV
frame = copy.copy(img)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
#show_image(hsv)
lower_blue = np.array([113, 40, 29])
upper_blue = np.array([123, 180, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
#show_image(mask)
result = cv2.bitwise_and(frame, frame, mask=mask)
#show_image(result)
blur = cv2.blur(result, (5, 5))
bw = cv2.cvtColor(blur, cv2.COLOR_HSV2BGR)
bw2 = cv2.cvtColor(bw, cv2.COLOR_BGR2GRAY)
ret, th3 = cv2.threshold(bw2, 30, 255, cv2.THRESH_BINARY)
# th3 = cv2.adaptiveThreshold(bw2,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
# cv2.THRESH_BINARY,11,2)
edges = cv2.Canny(th3, 100, 200)
th4 = copy.copy(th3)
perimeter = 0
j = 0
image, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# print len(contours)
# if(len(contours) > 5):
# continue
cnt = np.array([])
for i in range(len(contours)):
if (perimeter < cv2.contourArea(contours[i])):
perimeter = cv2.contourArea(contours[i])
j = i;
cnt = contours[j]
if (len(cnt) == 0):
return (-1, -1)
cv2.drawContours(frame, cnt, -1, (0, 255, 0), 3)
x = 0
y = 0
#print 'find goal'
#print len(cnt), j
#print cnt
for i in range(len(cnt)):
x = x + cnt[i][0][0]
y = y + cnt[i][0][1]
x = x/len(cnt)
y = y/len(cnt)
#print x, y
x = int(x)
y = int(y)
cv2.circle(frame, (x, y), 5, (255, 0, 255), -1)
cv2.imshow('image', frame)
cv2.imwrite('goal.jpg', frame)
k = cv2.waitKey(0)
return (int(x), int(y))