def test_canny_edge(): """ canny边缘检测。 :return: """ image_file = os.path.join(image_dir, "demo1.png") img = cv2.imread(image_file) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 高斯模糊,降低噪声 blurred = cv2.GaussianBlur(img, (3, 3), 0) # 灰度图像 gray = cv2.cvtColor(blurred, cv2.COLOR_RGB2GRAY) # 图像梯度 x_grad = cv2.Sobel(gray, cv2.CV_16SC1, 1, 0) y_grad = cv2.Sobel(gray, cv2.CV_16SC1, 0, 1) # 计算边缘 # 50和150参数必须符合1:3或者1:2 edge_output = cv2.Canny(x_grad, y_grad, 50, 150) cv2.imshow("edge", edge_output) dst = cv2.bitwise_and(img, img, mask=edge_output) cv2.imshow('cedge', dst) images = [img, blurred, gray, edge_output, dst] pil_image_demo.plt_images(images)
def test_filter(): """ 模糊/平滑。 :return: """ lena_img = misc.imread(os.path.join(image_dir, "lena_gray.jpg")) # print_image_pixel(lena_img) # lena_img = Image.fromarray(lena_img) # lena_img.show() # 高斯滤镜 blurred_lena_none = ndimage.gaussian_filter(lena_img, sigma=0) blurred_lena = ndimage.gaussian_filter(lena_img, sigma=3) very_blurred = ndimage.gaussian_filter(lena_img, sigma=5) # 均匀滤镜 local_mean = ndimage.uniform_filter(lena_img, size=11) # 锐化处理,通过增加拉普拉斯近似增加边缘权重 blurred_l = ndimage.gaussian_filter(lena_img, 3) filter_blurred_l = ndimage.gaussian_filter(blurred_l, 1) alpha = 30 sharpened = blurred_l + alpha * (blurred_l - filter_blurred_l) # 消噪处理 noisy = lena_img + 0.4 * lena_img.std() * np.random.random(lena_img.shape) gauss_denoised = ndimage.gaussian_filter(noisy, 2) med_denoised = ndimage.median_filter(noisy, 3) # 显示图像 image_arrays = [ lena_img, blurred_lena_none, blurred_lena, very_blurred, local_mean, sharpened, noisy, gauss_denoised, med_denoised ] images = ndarray_2_image(image_arrays) pil_image_demo.plt_images(images, 3)
def test_threshold(): """ 测试图像阈值。 :return: """ image_file1 = os.path.join(image_dir, "demo1.png") image1 = cv2.imread(image_file1) # 把输入图像灰度化 image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(image1, cv2.COLOR_RGB2GRAY) # gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) # show_image(gray) # 直接阈值化是对输入的单通道矩阵逐像素进行阈值分割。 ret, binary1 = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE) # show_image(binary) # 自适应阈值化能够根据图像不同区域亮度分布,改变阈值 binary2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 25, 10) # show_image(binary) # 根据平均像素值 h, w = gray.shape[:2] m = np.reshape(gray, [1, w*h]) mean = m.sum()/(w*h) common_logger.info("mean:{0}".format(mean)) ret, binary3 = cv2.threshold(gray, mean, 255, cv2.THRESH_BINARY) # show_image(binary) images = [image1, gray, binary1, binary2, binary3] pil_image_demo.plt_images(images)
def plt_image_test(): """ 显示图像。 :return: """ im_nums = np.arange(8) im = np.zeros([8, 8]) images = [] for im_num in im_nums: im = im.copy() im[im_num, im_num] = im_num images.append(im) pil_image_demo.plt_images(images, 3, interpolation='nearest')
def convert_image_color(): """ 图像颜色转换。 :return: """ image_file1 = os.path.join(image_dir, "demo1.png") image1 = cv2.imread(image_file1) image_cvt1 = cv2.cvtColor(image1, cv2.COLOR_BGR2HSV) image_cvt2 = cv2.cvtColor(image1, cv2.COLOR_RGB2HSV) image_cvt3 = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB) image_cvt4 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) image_cvt5 = cv2.cvtColor(image_cvt3, cv2.COLOR_RGB2GRAY) images = [image1, image_cvt1, image_cvt2, image_cvt3, image_cvt4, image_cvt5] pil_image_demo.plt_images(images)
def gray_dilation(): """ 灰度图的形态修改 :return: """ # 灰度值图像 im = np.zeros((64, 64)) np.random.seed(2) x, y = (63 * np.random.random((2, 8))).astype(np.int) im[x, y] = np.arange(8) # print_image_pixel(im) # 灰度膨胀 bigger_points = ndimage.grey_dilation(im, size=(5, 5), structure=np.ones((5, 5))) # print_image_pixel(bigger_points) square = np.zeros((16, 16)) square[4:-4, 4:-4] = 1 dist = ndimage.distance_transform_bf(square) dilate_dist = ndimage.grey_dilation(dist, size=(3, 3), structure=np.ones((3, 3))) images = [im, bigger_points, square, dist, dilate_dist] pil_image_demo.plt_images(images, 3) plt.figure(figsize=(12.5, 3)) plt.subplot(141) plt.imshow(im, interpolation='nearest') plt.axis('off') plt.subplot(142) plt.imshow(bigger_points, interpolation='nearest') plt.axis('off') plt.subplot(143) plt.imshow(dist, interpolation='nearest') plt.axis('off') plt.subplot(144) plt.imshow(dilate_dist, interpolation='nearest') plt.axis('off') plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) plt.show()
def test_histogram(): """ 测试直方图。 :return: """ # 构造图像 n = 10 length = 256 np.random.seed(1) im = np.zeros((length, length)) points = length * np.random.random((2, n**2)) im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 im = ndimage.gaussian_filter(im, sigma=length / (4. * n)) mask = (im > im.mean()).astype(np.float) mask += 0.1 * im img = mask + 0.2 * np.random.randn(*mask.shape) print("max:{0},min:{1}".format(np.max(img), np.min(img))) hist, bin_edges = np.histogram(img, bins=60) print("hist:{0}".format(hist)) print("bin_edges:{0}".format(bin_edges)) bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:]) binary_img = img > 0.5 images = [im, mask, binary_img] pil_image_demo.plt_images(images, 3) # 图像直方图 plt.figure(figsize=(11, 4)) plt.subplot(111) plt.plot(bin_centers, hist, lw=2) plt.axvline(0.5, color='r', ls='--', lw=2) plt.text(0.57, 0.8, 'histogram', fontsize=20, transform=plt.gca().transAxes) plt.yticks([]) plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) plt.show()
def edge_detect(): """ 边缘检测 :return: """ # 合成数据 im = np.zeros((256, 256)) im[64:-64, 64:-64] = 1 im = ndimage.rotate(im, 15, mode='constant') im_gf = ndimage.gaussian_filter(im, 8) # sobel检测 sx = ndimage.sobel(im_gf, axis=0, mode='constant') sy = ndimage.sobel(im_gf, axis=1, mode='constant') sob = np.hypot(sx, sy) images = [im, im_gf, sx, sy, sob] pil_image_demo.plt_images(images, 3)
def test_image_flip(): """ 翻转图像。 使用函数cv2.flip(img,flipcode)翻转图像,flipcode控制翻转效果。 flipcode = 0:沿x轴翻转 flipcode > 0:沿y轴翻转 flipcode < 0:x,y轴同时翻转 :return: """ image_file = os.path.join(image_dir, "demo1.png") img = cv2.imread(image_file) img_copy = img.copy() img_flip1 = cv2.flip(img, 0) img_flip2 = cv2.flip(img, 1) img_flip3 = cv2.flip(img, -1) images = [img_copy, img_flip1, img_flip2, img_flip3] pil_image_demo.plt_images(images)
def test_measurement(): """ 测试测量对象属性。 :return: """ # 合成图像 n = 10 length = 256 im = np.zeros((length, length)) points = length * np.random.random((2, n**2)) im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1 im = ndimage.gaussian_filter(im, sigma=length / (4. * n)) mask = im > im.mean() # 标记连接成分 label_im, nb_labels = ndimage.label(mask) print("区域数量:{0}".format(nb_labels)) # 计算每个区域的尺寸,均值等等 sizes = ndimage.sum(mask, label_im, range(nb_labels + 1)) mean_vals = ndimage.sum(im, label_im, range(1, nb_labels + 1)) print("各个区域的尺寸:{0}".format(sizes)) print("各个区域的平均尺寸:{0}".format(mean_vals)) # 计算尺寸小的连接成分 mask_size = sizes < 1000 remove_pixel = mask_size[label_im] print(remove_pixel.shape) label_im2 = label_im.copy() label_im2[remove_pixel] = 0 # 使用np.searchsorted重新分配标签 labels = np.unique(label_im2) label_im3 = np.searchsorted(labels, label_im2) # 找到关注的封闭对象区域 slice_x, slice_y = ndimage.find_objects(label_im3 == 4)[0] roi = im[slice_x, slice_y] images = [im, mask, label_im, label_im2, label_im3, roi] pil_image_demo.plt_images(images, 3)
def transform_shape(): """ 形状转换,剪裁,上下翻转,旋转。 :return: """ lena_img = imageio.imread(os.path.join(image_dir, "lena_gray.jpg")) width, height = lena_img.shape print("width:{0}, height:{1}".format(width, height)) # Cropping crop_lena = lena_img[round(width / 4):round(-width / 4), round(height / 4):round(-height / 4)] # up <-> down flip flip_ud_lena = np.flipud(lena_img) # rotation rotate_lena = ndimage.rotate(lena_img, 45) rotate_lena_noreshape = ndimage.rotate(lena_img, 45, reshape=False) images = [ lena_img, crop_lena, flip_ud_lena, rotate_lena, rotate_lena_noreshape ] pil_image_demo.plt_images(images)
def test_image_trans(): """ 测试图像变换 :return: """ image_file = os.path.join(image_dir, "demo1.png") img = cv2.imread(image_file) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) height, width, dim = img.shape # 执行Gamma矫正,小于1的值让暗部细节大量提升,同时亮部细节少量提升 img_gamma = ImageEnhanceCV.gamma_transform(img, 0.5) # 沿着横纵轴放大1.6倍,然后平移(-150,-240),最后沿原图大小截取,等效于裁剪并放大 m_crop = np.array([ [1.6, 0, -150], [0, 1.6, -240] ], dtype=np.float32) img_crop = cv2.warpAffine(img, m_crop, (width, height)) # x轴的剪切变换,角度15° theta = 15 * np.pi / 180 m_shear = np.array([ [1, np.tan(theta), 0], [0, 1, 0] ], dtype=np.float32) img_sheared = cv2.warpAffine(img, m_shear, (width, height)) # 顺时针旋转,角度15° m_rotate = np.array([ [np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0] ], dtype=np.float32) img_rotated = cv2.warpAffine(img, m_rotate, (width, height)) # show images images = [img, img_gamma, img_crop, img_sheared, img_rotated] pil_image_demo.plt_images(images)
def test_morphology(): """ 测试图像的数学形态学。 :return: """ show_content = False show_images = False el = ndimage.generate_binary_structure(2, 1) el_int = el.astype(np.int) if show_content: print(el) print(el_int) # 腐蚀:最小化滤镜 a = np.zeros((7, 7), dtype=np.int) a[1:6, 2:5] = 1 a_erosion1 = ndimage.binary_erosion(a).astype(a.dtype) a_erosion2 = ndimage.binary_erosion(a, structure=np.ones( (5, 5))).astype(a.dtype) if show_content: print(a) print(a_erosion1) print(a_erosion2) if show_images: image_arrays = [a, a_erosion1, a_erosion2] image_arrays = bin2gray(image_arrays) images = ndarray_2_image(image_arrays) pil_image_demo.plt_images(images, 3) # 膨胀:最大化滤镜 a = np.zeros((5, 5)) a[2, 2] = 1 a_dilation = ndimage.binary_dilation(a).astype(a.dtype) if show_content: print(a) print(a_dilation) if show_images: image_arrays = [a, a_dilation] image_arrays = bin2gray(image_arrays) images = ndarray_2_image(image_arrays) pil_image_demo.plt_images(images, 3) # 开操作:腐蚀 + 膨胀 square = np.zeros((32, 32)) square[10:-10, 10:-10] = 1 np.random.seed(2) x, y = (32 * np.random.random((2, 20))).astype(np.int) square[x, y] = 1 # 图像开操作 open_square = ndimage.binary_opening(square) # 先腐蚀后膨胀 eroded_square = ndimage.binary_erosion(square) reconstruction = ndimage.binary_propagation(eroded_square, mask=square) if show_images: image_arrays = [square, open_square, eroded_square, reconstruction] image_arrays = bin2gray(image_arrays) images = ndarray_2_image(image_arrays) pil_image_demo.plt_images(images, 2)