用import numpy as np from skimage.io import imread from skimage.color import rgb2hsv,hsv2rgb from skimage.exposure import equalize_hist import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体 plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 A=np.clip(B, 0, 1.0) # 对数字B的每个元素值进行两头截断,确保输出数组A的元素取值在0~1之间
时间: 2024-02-13 16:04:34 浏览: 155
好的,这段代码的功能是导入必要的Python库,并设置一些绘图常用的参数,以及展示如何使用`numpy.clip()`函数对数组进行截断操作。
代码如下:
```python
import numpy as np
from skimage.io import imread
from skimage.color import rgb2hsv, hsv2rgb
from skimage.exposure import equalize_hist
import matplotlib.pyplot as plt
# 设置绘图参数
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
# 对数字B的每个元素值进行两头截断,确保输出数组A的元素取值在0~1之间
A = np.clip(B, 0, 1.0)
```
需要注意的是,上述代码中的`B`是一个数组,可以替换成实际需要处理的数组。此外,`numpy.clip()`函数的第二个参数和第三个参数分别表示截断的下限和上限,可以根据实际情况自行调整。
相关问题
""" Contrast Limited Adaptive Histogram Equalization,CLAHE 对比度受限自适应直方图均衡 """ import cv2 # import numpy as np import matplotlib.pyplot as plt def show_img_with_matplotlib(color_img, title, pos): img_rgb = color_img[:, :, ::-1] plt.subplot(2, 5, pos) plt.imshow(img_rgb) plt.title(title, fontsize=8) plt.axis('off') def equalize_clahe_color_hsv(img): cla = cv2.createCLAHE(clipLimit=4.0) H, S, V = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV)) eq_V = cla.apply(V) eq_image = cv2.cvtColor(cv2.merge([H, S, eq_V]), cv2.COLOR_HSV2BGR) return eq_image def equalize_clahe_color_lab(img): cla = cv2.createCLAHE(clipLimit=4.0) L, a, b = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2Lab)) eq_L = cla.apply(L) eq_image = cv2.cvtColor(cv2.merge([eq_L, a, b]), cv2.COLOR_Lab2BGR) return eq_image def equalize_clahe_color_yuv(img): cla = cv2.createCLAHE(clipLimit=4.0) Y, U, V = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2YUV)) eq_Y = cla.apply(Y) eq_image = cv2.cvtColor(cv2.merge([eq_Y, U, V]), cv2.COLOR_YUV2BGR) return eq_image def equalize_clahe_color(img): cla = cv2.createCLAHE(clipLimit=4.0) channels = cv2.split(img) eq_channels = [] for ch in channels: eq_channels.append(cla.apply(ch)) eq_image = cv2.merge(eq_channels) return eq_image # 加载图像 image = cv2.imread('D:/Documents/python/OpenCV/image/008.jpg') gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 灰度图像应用 CLAHE clahe = cv2.createCLAHE(clipLimit=2.0) gray_image_clahe = clahe.apply(gray_image) # 使用不同 clipLimit 值 clahe.setClipLimit(5.0) gray_image_clahe_2 = clahe.apply(gray_image) clahe.setClipLimit(10.0) gray_image_clahe_3 = clahe.apply(gray_image) clahe.setClipLimit(20.0) gray_image_clahe_4 = clahe.apply(gray_image) # 彩色图像应用 CLAHE image_clahe_color = equalize_clahe_color(image) image_clahe_color_lab = equalize_clahe_color_lab(image) image_clahe_color_hsv = equalize_clahe_color_hsv(image) image_clahe_color_yuv = equalize_clahe_color_yuv(image) # 标题 plt.figure(figsize=(10, 4)) plt.suptitle("Color histogram equalization with cv2.equalizedHist() - not a good approach", fontsize=9, fontweight='bold') # 可视化 show_img_with_matplotlib(cv2.cvtColor(gray_image, cv2.COLOR_GRAY2BGR), "gray", 1) show_img_with_matplotlib(cv2.cvtColor(gray_image_clahe, cv2.COLOR_GRAY2BGR), "gray CLAHE clipLimit=2.0", 2) show_img_with_matplotlib(cv2.cvtColor(gray_image_clahe_2, cv2.COLOR_GRAY2BGR), "gray CLAHE clipLimit=5.0", 3) show_img_with_matplotlib(cv2.cvtColor(gray_image_clahe_3, cv2.COLOR_GRAY2BGR), "gray CLAHE clipLimit=10.0", 4) show_img_with_matplotlib(cv2.cvtColor(gray_image_clahe_4, cv2.COLOR_GRAY2BGR), "gray CLAHE clipLimit=20.0", 5) show_img_with_matplotlib(image, "color", 6) show_img_with_matplotlib(image_clahe_color, "clahe on each channel(BGR)", 7) show_img_with_matplotlib(image_clahe_color_lab, "clahe on each channel(LAB)", 8) show_img_with_matplotlib(image_clahe_color_hsv, "clahe on each channel(HSV)", 9) show_img_with_matplotlib(image_clahe_color_yuv, "clahe on each channel(YUV)", 10) plt.show()
CLAHE,即对比度受限自适应直方图均衡化,是一种用于增强图像对比度的方法。在计算图像直方图均衡化的过程中,CLAHE会先将图像分成许多小块,并对每个小块进行直方图均衡化。由于小块内的像素值范围较小,采取均衡化的结果会使得低对比度的区域增强,同时避免出现像素值过饱和的情况。CLAHE能够在保持图像整体视觉质量的同时,突出图像细节。在OpenCV库中,可以通过cv2.createCLAHE()函数来调用CLAHE算法。
用Python编写一个GUI界面,主界面有打开文件,打开文件后点击相关按钮可以对图片分别进行彩色转灰度图,调亮度、直方图均衡化、图像平移、旋转、仿射、插值缩放、透视、加噪、去噪点、Sobel边缘检测
好的,我们可以使用Python的Tkinter模块来实现GUI界面,使用OpenCV库来处理图片。以下是一个简单的示例代码,可以根据需要进行修改和扩展。
```python
import cv2
import numpy as np
import tkinter as tk
from tkinter import filedialog
class ImageProcessor:
def __init__(self):
self.img = None
self.processed_img = None
def open_file(self):
filepath = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.jpeg;*.png")])
if filepath:
self.img = cv2.imread(filepath)
self.processed_img = self.img.copy()
self.show_img(self.processed_img)
def save_file(self):
if self.processed_img is not None:
filepath = filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG file", "*.png")])
if filepath:
cv2.imwrite(filepath, self.processed_img)
def show_img(self, img):
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def gray(self):
if self.img is not None:
self.processed_img = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
self.show_img(self.processed_img)
def brightness(self, value):
if self.img is not None:
hsv = cv2.cvtColor(self.img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
v = np.clip(v + value, 0, 255)
hsv = cv2.merge([h, s, v])
self.processed_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
self.show_img(self.processed_img)
def equalize_hist(self):
if self.img is not None:
gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
self.processed_img = cv2.equalizeHist(gray)
self.show_img(self.processed_img)
def translate(self, x, y):
if self.img is not None:
rows, cols = self.img.shape[:2]
M = np.float32([[1, 0, x], [0, 1, y]])
self.processed_img = cv2.warpAffine(self.img, M, (cols, rows))
self.show_img(self.processed_img)
def rotate(self, angle):
if self.img is not None:
rows, cols = self.img.shape[:2]
M = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
self.processed_img = cv2.warpAffine(self.img, M, (cols, rows))
self.show_img(self.processed_img)
def affine(self, pts1, pts2):
if self.img is not None:
rows, cols = self.img.shape[:2]
M = cv2.getAffineTransform(pts1, pts2)
self.processed_img = cv2.warpAffine(self.img, M, (cols, rows))
self.show_img(self.processed_img)
def resize(self, width, height):
if self.img is not None:
self.processed_img = cv2.resize(self.img, (width, height), interpolation=cv2.INTER_LINEAR)
self.show_img(self.processed_img)
def perspective(self, pts1, pts2):
if self.img is not None:
rows, cols = self.img.shape[:2]
M = cv2.getPerspectiveTransform(pts1, pts2)
self.processed_img = cv2.warpPerspective(self.img, M, (cols, rows))
self.show_img(self.processed_img)
def add_noise(self):
if self.img is not None:
rows, cols = self.img.shape[:2]
noise = np.random.normal(0, 50, (rows, cols))
self.processed_img = cv2.add(self.img, noise.astype(np.uint8))
self.show_img(self.processed_img)
def remove_noise(self):
if self.img is not None:
gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
self.processed_img = cv2.medianBlur(gray, 5)
self.show_img(self.processed_img)
def sobel(self):
if self.img is not None:
gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
self.processed_img = cv2.magnitude(sobelx, sobely)
self.show_img(self.processed_img)
class App:
def __init__(self):
self.root = tk.Tk()
self.root.title("Image Processor")
self.processor = ImageProcessor()
self.create_menu()
self.create_toolbar()
self.create_canvas()
self.create_buttons()
self.root.mainloop()
def create_menu(self):
menubar = tk.Menu(self.root)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=self.processor.open_file)
filemenu.add_command(label="Save", command=self.processor.save_file)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=self.root.quit)
menubar.add_cascade(label="File", menu=filemenu)
self.root.config(menu=menubar)
def create_toolbar(self):
toolbar = tk.Frame(self.root)
toolbar.pack(side="top", fill="x")
gray_button = tk.Button(toolbar, text="Gray", command=self.processor.gray)
gray_button.pack(side="left")
brightness_scale = tk.Scale(toolbar, from_=-255, to=255, orient="horizontal")
brightness_scale.pack(side="left")
brightness_button = tk.Button(toolbar, text="Brightness", command=lambda: self.processor.brightness(brightness_scale.get()))
brightness_button.pack(side="left")
equalize_hist_button = tk.Button(toolbar, text="Equalize Hist", command=self.processor.equalize_hist)
equalize_hist_button.pack(side="left")
toolbar.add_separator()
translate_x_scale = tk.Scale(toolbar, from_=-100, to=100, orient="horizontal")
translate_x_scale.pack(side="left")
translate_y_scale = tk.Scale(toolbar, from_=-100, to=100, orient="horizontal")
translate_y_scale.pack(side="left")
translate_button = tk.Button(toolbar, text="Translate", command=lambda: self.processor.translate(translate_x_scale.get(), translate_y_scale.get()))
translate_button.pack(side="left")
rotate_scale = tk.Scale(toolbar, from_=-180, to=180, orient="horizontal")
rotate_scale.pack(side="left")
rotate_button = tk.Button(toolbar, text="Rotate", command=lambda: self.processor.rotate(rotate_scale.get()))
rotate_button.pack(side="left")
affine_button = tk.Button(toolbar, text="Affine", command=lambda: self.processor.affine(pts1, pts2))
affine_button.pack(side="left")
toolbar.add_separator()
resize_width_scale = tk.Scale(toolbar, from_=50, to=500, orient="horizontal")
resize_width_scale.pack(side="left")
resize_height_scale = tk.Scale(toolbar, from_=50, to=500, orient="horizontal")
resize_height_scale.pack(side="left")
resize_button = tk.Button(toolbar, text="Resize", command=lambda: self.processor.resize(resize_width_scale.get(), resize_height_scale.get()))
resize_button.pack(side="left")
perspective_button = tk.Button(toolbar, text="Perspective", command=lambda: self.processor.perspective(pts1, pts2))
perspective_button.pack(side="left")
toolbar.add_separator()
add_noise_button = tk.Button(toolbar, text="Add Noise", command=self.processor.add_noise)
add_noise_button.pack(side="left")
remove_noise_button = tk.Button(toolbar, text="Remove Noise", command=self.processor.remove_noise)
remove_noise_button.pack(side="left")
sobel_button = tk.Button(toolbar, text="Sobel", command=self.processor.sobel)
sobel_button.pack(side="left")
def create_canvas(self):
self.canvas = tk.Canvas(self.root, width=800, height=600)
self.canvas.pack(side="left", fill="both", expand=True)
self.canvas.bind("<Button-1>", self.on_canvas_click)
self.canvas.bind("<B1-Motion>", self.on_canvas_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_canvas_release)
self.canvas.bind("<Configure>", self.on_canvas_resize)
def create_buttons(self):
self.reset_button = tk.Button(self.root, text="Reset", command=self.reset_canvas)
self.reset_button.pack(side="bottom")
def reset_canvas(self):
self.canvas.delete("all")
self.pts1 = []
self.pts2 = []
def on_canvas_click(self, event):
x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
self.canvas.create_oval(x-5, y-5, x+5, y+5, fill="red")
if len(self.pts1) < 4:
self.pts1.append((x, y))
elif len(self.pts2) < 4:
self.pts2.append((x, y))
def on_canvas_drag(self, event):
if len(self.pts1) < 4 and len(self.pts2) < 4:
x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
self.canvas.create_oval(x-5, y-5, x+5, y+5, fill="red")
if len(self.pts1) < 4:
self.pts1.append((x, y))
elif len(self.pts2) < 4:
self.pts2.append((x, y))
def on_canvas_release(self, event):
if len(self.pts1) == 4 and len(self.pts2) == 4:
self.canvas.create_polygon(self.pts1, outline="green", fill="", width=2)
self.canvas.create_polygon(self.pts2, outline="blue", fill="", width=2)
def on_canvas_resize(self, event):
self.canvas.config(scrollregion=self.canvas.bbox("all"))
if __name__ == "__main__":
app = App()
```
在代码中,我们定义了一个ImageProcessor类来处理图像,包括打开文件、保存文件、灰度化、调亮度、直方图均衡化、图像平移、旋转、仿射、插值缩放、透视、加噪、去噪点、Sobel边缘检测等功能。然后我们定义了一个App类来实现GUI界面,包括菜单、工具栏、画布和按钮等组件,并且将ImageProcessor类的方法与这些组件进行绑定。在画布上,我们可以用鼠标左键来选择四个点,然后点击Affine或Perspective按钮来进行仿射或透视变换。
注意:在Windows系统中,使用OpenCV库显示图像时需要调用cv2.waitKey(0)函数来等待用户按下键盘,否则图像会无法显示。在其他系统中,可能需要调用cv2.imshow()函数来显示图像。
阅读全文