import cv2
def resize_by_ratio(image, width=None, height=None, inter=cv2.INTER_AREA):
img_new_size = None
(h, w) = image.shape[:2] # 获得高度和宽度
if width is None and height is None: # 如果输入的宽度和高度都为空
return image # 直接返回原图
if width is None:
h_ratio = height / float(h) # 输入高度 / 原始高度 得到比率
img_new_size = (int(w * h_ratio), height) # 将宽度缩放同样的比例
else:
w_ratio = width / float(w)
img_new_size = (width, int(h * w_ratio))
resized = cv2.resize(image, img_new_size, interpolation=inter)
return resized
def guo_lv(img,threshold):
r, c = img.shape
print(r,c)
for i in range(0,r):
for j in range(0,c):
if img[i,j]>threshold:
img[i,j] = 255
img = cv2.imread('../img/qian_ming2.png')
img = resize_by_ratio(img,width=320)
cv2.imshow('img1',img)
img=cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
threshold = 120
guo_lv(img,threshold)
cv2.imshow('img',img)
# cv2.imshow('img1',img)
# cv2.imshow('img2',img)
# ret,img_new = cv2.threshold(img, 155, 255, cv2.THRESH_BINARY)
# ret,thresh = cv2.threshold(img,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# cv2.imshow('img',img)
# cv2.imshow('img1',img)
cv2.waitKey(0)
原图:
执行程序后: