數(shù)字圖像處理的圖像操作
圖像操作在計(jì)算機(jī)視覺(jué)和圖像處理中發(fā)揮著至關(guān)重要的作用。這些操作對(duì)于諸如預(yù)處理、增強(qiáng)圖像質(zhì)量和啟用高級(jí)算法等任務(wù)至關(guān)重要。在計(jì)算機(jī)視覺(jué)中,諸如調(diào)整大小、裁剪、調(diào)整亮度/對(duì)比度/伽瑪和幾何變換等操作是基礎(chǔ)的。它們?cè)试S進(jìn)行高效的計(jì)算、提取感興趣區(qū)域、規(guī)范化圖像強(qiáng)度和幾何校準(zhǔn)。同樣,在圖像處理中,這些操作對(duì)于降采樣、裁剪不需要的區(qū)域、增強(qiáng)可見(jiàn)性和質(zhì)量以及執(zhí)行幾何操作都至關(guān)重要。

調(diào)整大小
在各種場(chǎng)景中,調(diào)整圖像大小是常見(jiàn)的,可以實(shí)現(xiàn)不同的目的,例如將圖像適應(yīng)特定尺寸或減小文件大小。圖像插值和重采樣是圖像處理和計(jì)算機(jī)視覺(jué)中用于調(diào)整圖像大小或比例的技術(shù)。
圖像插值
圖像插值是指根據(jù)已知像素值在圖像內(nèi)未知位置上估算像素值的過(guò)程。不同的插值方法使用不同的方式來(lái)估算未知像素的值。
最近鄰插值將未知像素位置的值分配為最近的已知像素值。這種方法簡(jiǎn)單但可能導(dǎo)致出現(xiàn)塊狀偽影和丟失細(xì)節(jié)。

最近鄰插值
雙線性插值考慮了四個(gè)最近的已知像素的值,并計(jì)算加權(quán)平均來(lái)估算未知像素的值。與最近鄰插值相比,它產(chǎn)生更平滑的結(jié)果,但仍可能引入一些模糊。
雙三次插值通過(guò)考慮更多的相鄰像素并使用三次多項(xiàng)式來(lái)估算像素值,擴(kuò)展了雙線性插值。這種方法可以提供更高質(zhì)量的結(jié)果,具有更平滑的過(guò)渡和更好的保留圖像細(xì)節(jié)。
import cv2
import numpy as np
def 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_image
SCALE = 4
# Load the image
image_path = "image.png"
image = cv2.imread(image_path)
# Resize the image using nearest neighbor interpolation
nearest_neighbor_resized = resize_image(image, scale=SCALE, interpolation=cv2.INTER_NEAREST)
# Resize the image using bilinear interpolation
bilinear_resized = resize_image(image, scale=SCALE, interpolation=cv2.INTER_LINEAR)
# Resize the image using bicubic interpolation
bicubic_resized = resize_image(image, scale=SCALE, interpolation=cv2.INTER_CUBIC)
裁剪
裁剪圖像的目的是去除不需要的內(nèi)容或聚焦于特定的感興趣區(qū)域。裁剪使您能夠優(yōu)化構(gòu)圖,消除干擾,并突出圖像中的重要元素。去除不必要或無(wú)關(guān)的部分可以創(chuàng)造出視覺(jué)上吸引人且具有影響力的圖像,有效地傳達(dá)預(yù)期的信息或主題。
可以使用不同的方法來(lái)確定裁剪區(qū)域:
- 手動(dòng)選擇:手動(dòng)裁剪涉及對(duì)圖像進(jìn)行視覺(jué)檢查并選擇要保留的所需區(qū)域。這種方法提供了靈活性,并允許基于攝影師或設(shè)計(jì)師的藝術(shù)判斷做主觀決定。
- 目標(biāo)檢測(cè):基于目標(biāo)檢測(cè)算法的自動(dòng)裁剪技術(shù)可以識(shí)別并提取圖像中的特定對(duì)象或主題。這些算法分析圖像并根據(jù)預(yù)定義的模式或經(jīng)過(guò)訓(xùn)練的模型定位對(duì)象。檢測(cè)到的對(duì)象可以作為裁剪區(qū)域,確保保留重要元素同時(shí)去除無(wú)關(guān)的背景或周?chē)鷧^(qū)域。
- 分割:可以使用圖像分割技術(shù),如語(yǔ)義分割或?qū)嵗指睿瑢D像分成有意義的區(qū)域。這些技術(shù)為不同的對(duì)象或區(qū)域分配標(biāo)簽或掩碼,使得可以裁剪特定的部分或隔離感興趣的特定區(qū)域。
import cv2
def crop_image(image, x, y, width, height):
cropped_image = image[y:y+height, x:x+width]
return cropped_image
# Example usage
image = 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()調(diào)整
亮度和對(duì)比度:
調(diào)整亮度和對(duì)比度對(duì)于增強(qiáng)圖像的可見(jiàn)性和提高視覺(jué)吸引力至關(guān)重要。調(diào)整亮度可以使圖像看起來(lái)更明亮或更暗,突顯曝光不足或曝光過(guò)度的區(qū)域的細(xì)節(jié)。對(duì)比度調(diào)整增強(qiáng)了光亮和陰暗區(qū)域之間的區(qū)別,使圖像顯得更清晰和更動(dòng)態(tài)。
通過(guò)控制亮度和對(duì)比度,您可以提高圖像的整體質(zhì)量和可讀性,確保重要的特征能夠清晰可辨。
import cv2
import numpy as np
image_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_image
def 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 image
image = cv2.imread(image_path)
# Adjust the brightness
brightness_adjusted = adjust_brightness(image, value=50)
# Adjust the contrast
contrast_adjusted = adjust_contrast(image, value=2)
# Display the original and adjusted images
cv2.imshow("Original", image)
cv2.imshow("Brightness Adjusted", brightness_adjusted)
cv2.imshow("Contrast Adjusted", contrast_adjusted)
cv2.waitKey(0)
cv2.destroyAllWindows()
直方圖均衡化
直方圖均衡化是一種用于增強(qiáng)對(duì)比度的技術(shù)。它通過(guò)重新分配像素強(qiáng)度值以涵蓋更廣范圍的值來(lái)實(shí)現(xiàn)這一目標(biāo)。其主要目標(biāo)是通過(guò)圖像獲得像素強(qiáng)度的更均勻分布。
通過(guò)重新分配像素強(qiáng)度,直方圖均衡化增強(qiáng)了圖像的對(duì)比度。
import cv2
import matplotlib.pyplot as plt
image_path = "cath.jpeg"
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Apply histogram equalization
equalized_image = cv2.equalizeHist(image)
# Calculate histograms
hist_original = cv2.calcHist([image], [0], None, [256], [0, 256])
hist_equalized = cv2.calcHist([equalized_image], [0], None, [256], [0, 256])
# Plot the histograms
plt.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 images
fig, 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()
均衡化圖像
線性縮放
線性縮放,也稱(chēng)為對(duì)比度拉伸,用于通過(guò)線性映射原始像素值到一個(gè)新范圍來(lái)調(diào)整圖像的亮度和對(duì)比度。該過(guò)程涉及根據(jù)圖像中的最小值和最大值重新縮放像素值,以利用完整的動(dòng)態(tài)范圍。
線性縮放允許對(duì)亮度和對(duì)比度的調(diào)整進(jìn)行精確控制。您可以根據(jù)特定要求定義所需的強(qiáng)度范圍。
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
image_path = "cath.jpeg"
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Calculate the minimum and maximum pixel values in the image
min_value = np.min(image)
max_value = np.max(image)
# Define the desired minimum and maximum intensity values for the output image
new_min = 5
new_max = 10
# Perform linear scaling
scaled_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 images
fig, 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()
線性縮放
伽馬校正
伽馬校正是一種用于糾正圖像輸入像素值與顯示輸出強(qiáng)度之間的非線性強(qiáng)度關(guān)系的技術(shù)。它考慮到人類(lèi)視覺(jué)系統(tǒng)對(duì)光的非線性響應(yīng),并旨在實(shí)現(xiàn)更準(zhǔn)確和感知一致的圖像表示。
相機(jī)捕捉或存儲(chǔ)在圖像文件中的像素值與人類(lèi)感知亮度之間的關(guān)系是非線性的。換句話說(shuō),像素值的線性增加并不導(dǎo)致感知亮度的線性增加。這種非線性關(guān)系是由于成像傳感器和人類(lèi)視覺(jué)系統(tǒng)的響應(yīng)特性導(dǎo)致的。
伽馬校正基于一個(gè)稱(chēng)為伽馬(γ)的參數(shù)。伽馬值表示輸入像素值和顯示輸出強(qiáng)度之間的關(guān)系。它是兩者之間非線性映射的度量。
伽馬校正對(duì)像素值應(yīng)用冪律變換,調(diào)整強(qiáng)度值以校正非線性響應(yīng)。伽馬校正的公式如下:
校正值 = 輸入值 ^ (1 / 伽馬)
這里,輸入值代表原始像素值,校正值代表調(diào)整后的像素值。
伽馬校正的主要作用是補(bǔ)償非線性強(qiáng)度關(guān)系,確保圖像中的顏色和細(xì)節(jié)得到準(zhǔn)確的表示。伽馬校正發(fā)揮重要作用的方式如下:
- 亮度補(bǔ)償:伽馬校正有助于彌補(bǔ)捕捉和顯示設(shè)備之間亮度響應(yīng)的差異。它確保顯示圖像中的感知亮度水平與原始場(chǎng)景一致。
- 對(duì)比度增強(qiáng):伽馬校正可以通過(guò)重新分配色調(diào)值來(lái)增強(qiáng)圖像的對(duì)比度。根據(jù)伽馬值的不同,它可以有效地強(qiáng)調(diào)圖像的暗區(qū)域或亮區(qū)域中的細(xì)節(jié)。
- 色彩準(zhǔn)確性:伽馬校正有助于實(shí)現(xiàn)準(zhǔn)確的顏色表示。通過(guò)調(diào)整伽馬值,可以改善顏色再現(xiàn),確保顏色看起來(lái)更自然且忠實(shí)于原始場(chǎng)景。
- 色調(diào)映射:在高動(dòng)態(tài)范圍(HDR)成像中,伽馬校正常常作為色調(diào)映射技術(shù)的一部分,將場(chǎng)景的廣泛動(dòng)態(tài)范圍映射到顯示設(shè)備的有限動(dòng)態(tài)范圍。伽馬校正有助于保持陰影和高光區(qū)域的細(xì)節(jié),防止信息丟失。
- 感知一致性:伽馬校正旨在實(shí)現(xiàn)感知上一致的圖像,其中顯示的強(qiáng)度與人類(lèi)視覺(jué)感知一致。通過(guò)校正非線性響應(yīng),伽馬校正確保圖像對(duì)觀眾呈現(xiàn)出視覺(jué)上愉悅和逼真的效果。
import cv2
import numpy as np
image_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 image
image = cv2.imread(image_path)
# Adjust the gamma value
gamma_value = 1.5
gamma_corrected = adjust_gamma(image, gamma_value)
# Display the original and gamma-corrected images
cv2.imshow("Original", image)
cv2.imshow("Gamma Corrected", gamma_corrected)
cv2.waitKey(0)
cv2.destroyAllWindows()
伽馬校正
幾何變換
幾何變換使圖像的透視、方向和空間關(guān)系發(fā)生變化。這些變換為圖像對(duì)齊、目標(biāo)檢測(cè)、圖像注冊(cè)等任務(wù)提供了基本工具。
(1) 平移
平移是一種基本的幾何變換,涉及將圖像水平或垂直移動(dòng)指定的距離。
import cv2
import numpy as np
image_path = "cath.jpeg"
image = cv2.imread(image_path)
# Define the translation matrix
tx = 100 # pixels to shift in the x-axis
ty = 50 # pixels to shift in the y-axis
translation_matrix = np.float32([[1, 0, tx], [0, 1, ty]])
# Apply translation
translated_image = cv2.warpAffine(image, translation_matrix, (image.shape[1], image.shape[0]))
# Display the original and translated images
cv2.imshow("Original", image)
cv2.imshow("Translated", translated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
平移
(2) 縮放
縮放是指調(diào)整圖像的大小,可以通過(guò)對(duì)所有維度應(yīng)用統(tǒng)一的縮放因子,或者使用不同的縮放因子來(lái)調(diào)整不同的維度。已縮放。
# Define the scaling factors
scale_x = 1.5 # scaling factor for the x-axis
scale_y = 0.8 # scaling factor for the y-axis
# Apply scaling
scaled_image = cv2.resize(image, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)
# Display the original and scaled images
cv2.imshow("Original", image)
cv2.imshow("Scaled", scaled_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
縮放
(3) 旋轉(zhuǎn)
旋轉(zhuǎn)是一種幾何變換,涉及圍繞中心點(diǎn)按指定角度更改圖像的方向。
# Define the rotation angle
angle = 30
# Perform rotation
rows, 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 images
cv2.imshow("Original", image)
cv2.imshow("Rotated", rotated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
旋轉(zhuǎn)


























