圖像操作在計算機視覺和圖像處理中發揮著至關重要的作用。這些操作對于諸如預處理、增強圖像質量和啟用高級算法等任務至關重要。在計算機視覺中,諸如調整大小、裁剪、調整亮度/對比度/伽瑪和幾何變換等操作是基礎的。它們允許進行高效的計算、提取感興趣區域、規范化圖像強度和幾何校準。同樣,在圖像處理中,這些操作對于降采樣、裁剪不需要的區域、增強可見性和質量以及執行幾何操作都至關重要。
在各種場景中,調整圖像大小是常見的,可以實現不同的目的,例如將圖像適應特定尺寸或減小文件大小。圖像插值和重采樣是圖像處理和計算機視覺中用于調整圖像大小或比例的技術。
圖像插值是指根據已知像素值在圖像內未知位置上估算像素值的過程。不同的插值方法使用不同的方式來估算未知像素的值。
最近鄰插值將未知像素位置的值分配為最近的已知像素值。這種方法簡單但可能導致出現塊狀偽影和丟失細節。
最近鄰插值
雙線性插值考慮了四個最近的已知像素的值,并計算加權平均來估算未知像素的值。與最近鄰插值相比,它產生更平滑的結果,但仍可能引入一些模糊。
雙三次插值通過考慮更多的相鄰像素并使用三次多項式來估算像素值,擴展了雙線性插值。這種方法可以提供更高質量的結果,具有更平滑的過渡和更好的保留圖像細節。
import cv2import numpy as npdef resize_image(image, scale, interpolation): width = int(image.shape[1] * scale) height = int(image.shape[0] * scale) resized_image = cv2.resize(image, (width, height), interpolation=interpolation) return resized_imageSCALE = 4# Load the imageimage_path = "image.png"image = cv2.imread(image_path)# Resize the image using nearest neighbor interpolationnearest_neighbor_resized = resize_image(image, scale=SCALE, interpolation=cv2.INTER_NEAREST)# Resize the image using bilinear interpolationbilinear_resized = resize_image(image, scale=SCALE, interpolation=cv2.INTER_LINEAR)# Resize the image using bicubic interpolationbicubic_resized = resize_image(image, scale=SCALE, interpolation=cv2.INTER_CUBIC)
裁剪圖像的目的是去除不需要的內容或聚焦于特定的感興趣區域。裁剪使您能夠優化構圖,消除干擾,并突出圖像中的重要元素。去除不必要或無關的部分可以創造出視覺上吸引人且具有影響力的圖像,有效地傳達預期的信息或主題。
可以使用不同的方法來確定裁剪區域:
import cv2def crop_image(image, x, y, width, height): cropped_image = image[y:y+height, x:x+width] return cropped_image# Example usageimage = cv2.imread("cath.jpeg")cropped_image = crop_image(image, x=400, y=500, width=300, height=200)cv2.imshow("Cropped Image", cropped_image)cv2.waitKey(0)cv2.destroyAllWindows()
亮度和對比度:
調整亮度和對比度對于增強圖像的可見性和提高視覺吸引力至關重要。調整亮度可以使圖像看起來更明亮或更暗,突顯曝光不足或曝光過度的區域的細節。對比度調整增強了光亮和陰暗區域之間的區別,使圖像顯得更清晰和更動態。
通過控制亮度和對比度,您可以提高圖像的整體質量和可讀性,確保重要的特征能夠清晰可辨。
import cv2import numpy as npimage_path = "cath.jpeg"def adjust_brightness(image, value): # Convert the image to the HSV color space hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # Split the channels h, s, v = cv2.split(hsv) # Apply the brightness adjustment v = cv2.add(v, value) # Clamp the values to the valid range of 0-255 v = np.clip(v, 0, 255) # Merge the channels back together hsv = cv2.merge((h, s, v)) # Convert the image back to the BGR color space adjusted_image = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) return adjusted_imagedef adjust_contrast(image, value): # Convert the image to the LAB color space lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB) # Split the channels l, a, b = cv2.split(lab) # Apply the contrast adjustment l = cv2.multiply(l, value) # Clamp the values to the valid range of 0-255 l = np.clip(l, 0, 255) # Merge the channels back together lab = cv2.merge((l, a, b)) # Convert the image back to the BGR color space adjusted_image = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR) return adjusted_image# Load the imageimage = cv2.imread(image_path)# Adjust the brightnessbrightness_adjusted = adjust_brightness(image, value=50)# Adjust the contrastcontrast_adjusted = adjust_contrast(image, value=2)# Display the original and adjusted imagescv2.imshow("Original", image)cv2.imshow("Brightness Adjusted", brightness_adjusted)cv2.imshow("Contrast Adjusted", contrast_adjusted)cv2.waitKey(0)cv2.destroyAllWindows()
直方圖均衡化是一種用于增強對比度的技術。它通過重新分配像素強度值以涵蓋更廣范圍的值來實現這一目標。其主要目標是通過圖像獲得像素強度的更均勻分布。
通過重新分配像素強度,直方圖均衡化增強了圖像的對比度。
import cv2import matplotlib.pyplot as pltimage_path = "cath.jpeg"image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)# Apply histogram equalizationequalized_image = cv2.equalizeHist(image)# Calculate histogramshist_original = cv2.calcHist([image], [0], None, [256], [0, 256])hist_equalized = cv2.calcHist([equalized_image], [0], None, [256], [0, 256])# Plot the histogramsplt.figure(figsize=(10, 5))plt.subplot(1, 2, 1)plt.plot(hist_original, color='b')plt.title("Original Image Histogram")plt.xlabel("Pixel Intensity")plt.ylabel("Frequency")plt.subplot(1, 2, 2)plt.plot(hist_equalized, color='r')plt.title("Equalized Image Histogram")plt.xlabel("Pixel Intensity")plt.ylabel("Frequency")plt.tight_layout()plt.show()
直方圖
# Display the original and equalized imagesfig, axes = plt.subplots(1, 2, figsize=(10, 5))axes[0].imshow(image, cmap='gray')axes[0].set_title("Original")axes[0].axis("off")axes[1].imshow(equalized_image, cmap='gray')axes[1].set_title("Equalized")axes[1].axis("off")plt.tight_layout()plt.show()
均衡化圖像
線性縮放,也稱為對比度拉伸,用于通過線性映射原始像素值到一個新范圍來調整圖像的亮度和對比度。該過程涉及根據圖像中的最小值和最大值重新縮放像素值,以利用完整的動態范圍。
線性縮放允許對亮度和對比度的調整進行精確控制。您可以根據特定要求定義所需的強度范圍。
import cv2import numpy as npimport matplotlib.pyplot as plt# Load the imageimage_path = "cath.jpeg"image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)# Calculate the minimum and maximum pixel values in the imagemin_value = np.min(image)max_value = np.max(image)# Define the desired minimum and maximum intensity values for the output imagenew_min = 5new_max = 10# Perform linear scalingscaled_image = cv2.convertScaleAbs(image, alpha=(new_max - new_min) / (max_value - min_value), beta=new_min - min_value * (new_max - new_min) / (max_value - min_value))# Display the original and scaled imagesfig, axes = plt.subplots(1, 2, figsize=(10, 5))axes[0].imshow(cv2.cvtColor(image, cv2.COLOR_GRAY2RGB))axes[0].set_title("Original")axes[0].axis("off")axes[1].imshow(scaled_image, cmap='gray')axes[1].set_title("Scaled")axes[1].axis("off")plt.tight_layout()plt.show()
線性縮放
伽馬校正是一種用于糾正圖像輸入像素值與顯示輸出強度之間的非線性強度關系的技術。它考慮到人類視覺系統對光的非線性響應,并旨在實現更準確和感知一致的圖像表示。
相機捕捉或存儲在圖像文件中的像素值與人類感知亮度之間的關系是非線性的。換句話說,像素值的線性增加并不導致感知亮度的線性增加。這種非線性關系是由于成像傳感器和人類視覺系統的響應特性導致的。
伽馬校正基于一個稱為伽馬(γ)的參數。伽馬值表示輸入像素值和顯示輸出強度之間的關系。它是兩者之間非線性映射的度量。
伽馬校正對像素值應用冪律變換,調整強度值以校正非線性響應。伽馬校正的公式如下:
校正值 = 輸入值 ^ (1 / 伽馬)
這里,輸入值代表原始像素值,校正值代表調整后的像素值。
伽馬校正的主要作用是補償非線性強度關系,確保圖像中的顏色和細節得到準確的表示。伽馬校正發揮重要作用的方式如下:
import cv2import numpy as npimage_path = "cath.jpeg"def adjust_gamma(image, gamma): # Build a lookup table mapping the input pixel values to the corrected gamma values lookup_table = np.array([((i / 255.0) ** gamma) * 255 for i in np.arange(0, 256)]).astype(np.uint8) # Apply gamma correction using the lookup table gamma_corrected = cv2.LUT(image, lookup_table) return gamma_corrected# Load the imageimage = cv2.imread(image_path)# Adjust the gamma valuegamma_value = 1.5gamma_corrected = adjust_gamma(image, gamma_value)# Display the original and gamma-corrected imagescv2.imshow("Original", image)cv2.imshow("Gamma Corrected", gamma_corrected)cv2.waitKey(0)cv2.destroyAllWindows()
伽馬校正
幾何變換使圖像的透視、方向和空間關系發生變化。這些變換為圖像對齊、目標檢測、圖像注冊等任務提供了基本工具。
(1) 平移
平移是一種基本的幾何變換,涉及將圖像水平或垂直移動指定的距離。
import cv2import numpy as npimage_path = "cath.jpeg"image = cv2.imread(image_path)# Define the translation matrixtx = 100 # pixels to shift in the x-axisty = 50 # pixels to shift in the y-axistranslation_matrix = np.float32([[1, 0, tx], [0, 1, ty]])# Apply translationtranslated_image = cv2.warpAffine(image, translation_matrix, (image.shape[1], image.shape[0]))# Display the original and translated imagescv2.imshow("Original", image)cv2.imshow("Translated", translated_image)cv2.waitKey(0)cv2.destroyAllWindows()
平移
(2) 縮放
縮放是指調整圖像的大小,可以通過對所有維度應用統一的縮放因子,或者使用不同的縮放因子來調整不同的維度。已縮放。
# Define the scaling factorsscale_x = 1.5 # scaling factor for the x-axisscale_y = 0.8 # scaling factor for the y-axis# Apply scalingscaled_image = cv2.resize(image, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)# Display the original and scaled imagescv2.imshow("Original", image)cv2.imshow("Scaled", scaled_image)cv2.waitKey(0)cv2.destroyAllWindows()
縮放
(3) 旋轉
旋轉是一種幾何變換,涉及圍繞中心點按指定角度更改圖像的方向。
# Define the rotation angleangle = 30# Perform rotationrows, cols = image.shape[:2]rotation_matrix = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)rotated_image = cv2.warpAffine(image, rotation_matrix, (cols, rows))# Display the original and rotated imagescv2.imshow("Original", image)cv2.imshow("Rotated", rotated_image)cv2.waitKey(0)cv2.destroyAllWindows()
旋轉
本文鏈接:http://www.www897cc.com/showinfo-26-45470-0.html數字圖像處理的圖像操作
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 淺淺介紹下中文分詞,用這些庫搞定
下一篇: 多線程操作數據庫時,您悠著點