import cv2def 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 resizeddef guo_lv(img,threshold):r, c = img.shapeprint(r,c)for i in range(0,r):for j in range(0,c):if img[i,j]>threshold:img[i,j] = 255img = 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)
原图:
执行程序后: