图像处理第三次实验-图像预处理

一.对比度优化方法CLAHE 1.使用软件fiji优化图片序列 实验过程: 1)下载安装Fiji 2)解压30-T4N2, 24_pre_waterT1C.nii.zip 3)打开一张图片 4)在fiji中, Process -> Enhance Local Contrast(CLAHE, Contrast Limited Adaptive Histogram Equalization 直方图均衡化算法),将参数设置为如下,观察图片变化 blocksize = 64 histogram bins = 128 max slope = 2.0 图片效果如下 原图 处理后的图 可以看到部分区域对比度增强,图像中体现的信息也更为突出。 2.使用fiji脚本批量处理一组图片 1)使用fiji打开16-T2N2,33+_post_waterT1C.nii.gz 2)使用Fiji’s scripting editor,将语言更改为IJ1 Macro,运行脚本 3)最后点击菜单栏File → Save As → Image Sequence 保存为png格式,存储在文件夹中。 二.图像x-ray去噪 使用median filter算法,批处理文件/x-ray-images-enhancement-master/images/ 中值滤波器:中值滤波器是众所周知的阶数统计滤波器之一,因为它对某些特定的噪声类型(例如“高斯”,“随机”和“盐和胡椒”噪声)具有良好的性能。根据中值滤波器,将M×M邻域的中心像素替换为相应窗口的中值。注意,噪声像素被认为与中值有很大差异。使用这种思想,中值滤波器可以消除这种类型的噪声问题。 批处理代码实现如下: path='images/' file_list = [f for f in os.listdir(path) if not f.startswith('.')] file_num = len(file_list) i = 1 print("file_num", file_num) for img_dir in file_list: im = Image.open("images/"+img_dir) for sz in [3, 7, 15]: im1 = im.filter(ImageFilter.MedianFilter(size=sz)) im.save("imagesProcessed/"+"spnoise_"+str(sz)+"_"+img_dir) print(img_dir + " processed") 这里我们通过调节size来观察效果。 ...

March 26, 2021 · 1 min · Loyio Hex

图像处理第二次试验-裁剪图像

医学图像预处理 1)搭建运行环境,运行Brain Tumor Detection代码中裁剪功能 预先安装好相关模块,安装Jupyter Notebook交互式计算环境 conda install jupyter 首先导入相关包 import tensorflow as tf from tensorflow.keras.layers import Conv2D, Input, ZeroPadding2D, BatchNormalization, Activation, MaxPooling2D, Flatten, Dense from tensorflow.keras.models import Model, load_model from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score from sklearn.utils import shuffle import cv2 import imutils import numpy as np import matplotlib.pyplot as plt import time from os import listdir %matplotlib inline 因为这里只是进行图形预处理,对Brain Tumor图片进行裁剪,主要用到的包是cv2, imutils, numpy, matplotlib.pyplot 然后是运行定义裁剪脑轮廓(查找大脑的顶部、底部、左端、右端的极点)的函数(crop_brain_contour) def crop_brain_contour(image, plot=False): #import imutils #import cv2 #from matplotlib import pyplot as plt # Convert the image to grayscale, and blur it slightly gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (5, 5), 0) # Threshold the image, then perform a series of erosions + # dilations to remove any small regions of noise thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1] thresh = cv2.erode(thresh, None, iterations=2) thresh = cv2.dilate(thresh, None, iterations=2) # Find contours in thresholded image, then grab the largest one cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) c = max(cnts, key=cv2.contourArea) # Find the extreme points extLeft = tuple(c[c[:, :, 0].argmin()][0]) extRight = tuple(c[c[:, :, 0].argmax()][0]) extTop = tuple(c[c[:, :, 1].argmin()][0]) extBot = tuple(c[c[:, :, 1].argmax()][0]) # crop new image out of the original image using the four extreme points (left, right, top, bottom) new_image = image[extTop[1]:extBot[1], extLeft[0]:extRight[0]] if plot: plt.figure() plt.subplot(1, 2, 1) plt.imshow(image) plt.tick_params(axis='both', which='both', top=False, bottom=False, left=False, right=False, labelbottom=False, labeltop=False, labelleft=False, labelright=False) plt.title('Original Image') plt.subplot(1, 2, 2) plt.imshow(new_image) plt.tick_params(axis='both', which='both', top=False, bottom=False, left=False, right=False, labelbottom=False, labeltop=False, labelleft=False, labelright=False) plt.title('Cropped Image') plt.show() return new_image 下面我简单说一下我对这个函数的理解(当然函数中已有原作者的解释): ...

March 22, 2021 · 3 min · Loyio Hex

图像处理第一次实验-初识CV

1.jpg 2.jpg 1.对1.jpg 分别作灰度化, 模糊化处理. 代码如下 """ @Project: imageProcessing @Author: loyio @Date: 3/20/21 """ from PIL import Image, ImageFilter if __name__ == '__main__': # greyscale imgfileOne = "Sample/1" sample_img = Image.open(imgfileOne+".jpg").convert('L') sample_img.save(imgfileOne+"_processed_gray.jpg") # Blur # sample_img = Image.open(imgfileOne+".jpg").filter(ImageFilter.BLUR) sample_img = Image.open(imgfileOne+".jpg").filter(ImageFilter.BoxBlur(5)) sample_img.save(imgfileOne + "_processed_blur.jpg") 图片效果如下 灰度处理 模糊处理 2.对2.jpg生成手绘效果 代码如下 """ @Project: imageProcessing @Author: loyio @Date: 3/20/21 """ from PIL import Image, ImageFilter import numpy as np if __name__ == '__main__': # Paint imgfileTwo = "Sample/2" sample_img_ary = np.asarray(Image.open(imgfileTwo+".jpg").convert('L')).astype('float') depth = 10. grad_x, grad_y = np.gradient(sample_img_ary) grad_x = grad_x * depth / 100. grad_y = grad_y * depth / 100. A = np.sqrt(grad_x ** 2 + grad_y ** 2 + 1.) uni_x = grad_x / A uni_y = grad_y / A uni_z = 1. / A vec_el = np.pi / 2.2 vec_az = np.pi / 4. dx = np.cos(vec_el) * np.cos(vec_az) dy = np.cos(vec_el) * np.sin(vec_az) dz = np.sin(vec_el) sample_processed_ary = (255 * (dx*uni_x + dy*uni_y + dz*uni_z)).clip(0, 255) im = Image.fromarray(sample_processed_ary.astype('uint8')) im.save(imgfileTwo+"_processed_handpaint.jpg") 首先将图片灰度化,然后转换为float类型,存放在numpy array中 通过np.gradient求灰度图像的梯度(即灰度的变化率),将其赋值给grad_x, grad_y ,并根据深度级别计算新的梯度,同时归一化。将其控制在(0,1) 为x,y轴梯度构建三维归一化单位坐标系。 建立光源效果,可以将np.cos(vec_el)分析为单位射线在地平面上的投影长度。 dx,dy和dz是光源在x / y / z方向上的影响。 梯度与光源相互作用,最终将梯度转换为灰度。即sample_processed_ary = 255 * (dx*uni_x + dy*uni_y + dz*uni_z) 为避免越过边界,最后还要调用函数.clip(0,255) 图片效果如下 ...

March 20, 2021 · 1 min · Loyio Hex

pip安装模块时报错 ModuleNotFoundError:No module named '_ctypes'

最近一直在折腾GoogleDrive,用了rclone,又装AutoClone,最近又用上了gclone 在安装AutoClone依赖文件时报错 ERROR: Command errored out with exit status 1: command: /usr/local/python3/bin/python3.8 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-c6woj60b/progress/setup.py'"'"'; __file__='"'"'/tmp/pip-install-c6woj60b/progress/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: /tmp/pip-install-c6woj60b/progress/ Complete output (11 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/local/python3/lib/python3.8/site-packages/setuptools/__init__.py", line 20, in <module> from setuptools.dist import Distribution, Feature File "/usr/local/python3/lib/python3.8/site-packages/setuptools/dist.py", line 35, in <module> from setuptools import windows_support File "/usr/local/python3/lib/python3.8/site-packages/setuptools/windows_support.py", line 2, in <module> import ctypes File "/usr/local/python3/lib/python3.8/ctypes/__init__.py", line 7, in <module> from _ctypes import Union, Structure, Array ModuleNotFoundError: No module named '_ctypes' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Google了一下,找到解决方法是安装 libffi-devel ...

May 6, 2020 · 1 min · Loyio Hex