img = imread('image.jpg'); img_gray = rgb2gray(img); [m, n] = size(img_gray); mask = ones(3, 3) / 9;
时间: 2024-05-19 15:13:54 浏览: 133
filtered_image = conv2(double(img_gray), mask, 'same');
This code snippet reads in an image "image.jpg", converts it to grayscale, and then creates a 3x3 averaging mask. The conv2 function is then used to convolve the image with the mask to perform a 2D spatial filtering operation, resulting in a filtered_image. The 'same' argument in the conv2 function ensures that the output image is the same size as the input image.
相关问题
优化这段代码import cv2 import imutils import numpy as np img = cv2.imread('D:\pycharm\PycharmProjects\pythonProject\p1\p1.jpg', cv2.IMREAD_COLOR) img = cv2.resize(img, (600, 400)) cv2.imshow('Origin image', img) img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) img_gray = cv2.bilateralFilter(img_gray, 13, 15, 15) img_edged = cv2.Canny(img_gray, 30, 200) cv2.imshow('edged image', img_edged) img_contours = cv2.findContours(img_edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) img_contours = imutils.grab_contours(img_contours) img_contours = sorted(img_contours, key=cv2.contourArea, reverse=True)[:10] screenCnt = None for c in img_contours: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.018 * peri, True) if len(approx) == 4: screenCnt = approx break if screenCnt is None: detected = 0 print("No contour detected") else: detected = 1 if detected == 1: cv2.drawContours(img, [screenCnt], -1, (0, 0, 255), 3) mask = np.zeros(img_gray.shape, np.uint8) new_image = cv2.drawContours(mask, [screenCnt], 0, 255, -1, ) cv2.imshow('mask_image', new_image) new_image = cv2.bitwise_and(img, img, mask=mask) (x, y) = np.where(mask == 255) (topx, topy) = (np.min(x), np.min(y)) (bottomx, bottomy) = (np.max(x), np.max(y)) cropped = img_gray[topx:bottomx + 1, topy:bottomy + 1] cropped = cv2.resize(cropped, (400, 200)) cv2.imshow('Cropped', cropped) cv2.waitKey(0) cv2.destroyAllWindows()
这段代码主要是对一张图片进行边缘检测,并找出图片中的一个矩形区域进行裁剪。下面是对代码的一些优化建议:
1. 将代码拆分成多个函数,增加代码的可读性和可维护性。
2. 将文件路径字符串改为使用原始字符串(raw string),以避免转义字符带来的问题。
3. 考虑使用命令行参数或配置文件来指定输入文件路径和其他参数,以增加代码的灵活性。
4. 添加错误处理机制,例如检查文件是否存在,处理可能出现的异常情况。
5. 使用`with`语句来管理资源,例如`cv2.VideoCapture`和`cv2.imshow`,以确保资源的正确释放。
6. 使用`argparse`模块来解析命令行参数,以方便指定不同的参数和选项。
7. 使用更具描述性的变量名,以增加代码的可读性。
8. 添加注释来解释代码的功能和逻辑。
9. 考虑使用适当的异常处理机制,例如在无法找到矩形区域时抛出异常或返回错误码。
以上是对代码的一些优化建议,你可以根据实际需求进行调整。
""" 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算法。
阅读全文