我自己的原文哦~?? ?https://blog.51cto.com/whaosoft/13241694
一、CV創建自定義圖像濾鏡
? 熱圖濾鏡
? ? 這組濾鏡提供了各種不同的藝術和風格化光學圖像捕捉方法。例如,熱濾鏡會將圖像轉換為“熱圖”,而卡通濾鏡則提供生動的圖像,這些圖像看起來就像是漫畫書制作的。最接近自然色彩以及海灘和自然場景的是 VSCO 濾鏡。如果要減少工業感,可以對 Instagram 應用濾鏡進行大量投資。將這個簡單的灰度圖轉換為彩色圖像。這將是灰度濾鏡之一。最后,讓我們考慮油畫濾鏡,OpenCV 通過一種風格化技術實現了該濾鏡,該技術可創建看起來像油畫的紋理效果。用戶只需幾行代碼即可通過 OpenCV 和 Python 輕松使用它們來增強圖像。
? ? 熱成像非常適合在夜間或存在輕微霧、雨或煙等遮擋物的情況下生成圖像。例如,前視紅外或 FLIR 攝像機可用于為軍用和民用飛機提供夜視功能,或用于安全和監視。
import cv2
img = cv2.imread('image.jpg')
#applying filter
color_image = cv2.applyColorMap(img, cv2.COLORMAP_JET)
cv2.imshow('Image',color_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
? ? 卡通濾鏡
? ? 使用我們舉世聞名的 Cartoonizer 效果將任何照片變成卡通!只需單擊一下即可了解為什么它是我們最喜愛的藝術類別。
? ? 這是讀取圖像后的片段代碼,我們必須應用灰色,然后模糊圖像。
import cv2
image = cv2.imread('image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurImage = cv2.medianBlur(image, 1)
edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9)
color = cv2.bilateralFilter(image, 9, 200, 200)
cartoon = cv2.bitwise_and(color, color, mask = edges)
cv2.imshow('Image',cartoon)
cv2.waitKey(0)
cv2.destroyAllWindows()
? ??VSCO 濾鏡
? ? 要創建 VSCO 風格的濾鏡效果,您需要使用鮮艷的預設。類似 VSCO 的濾鏡非常適合各種圖像。讓您的圖像呈現出色彩鮮艷、充滿活力的外觀,非常適合自然和海灘場景等主題。
import cv2
import numpy as np
def colorful_vibrant_filter(image):"""Apply a colorful and vibrant filter to the input image.Args:image (numpy.ndarray): The input image.Returns:numpy.ndarray: The filtered image."""# Convert the image to HSV color spacehsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)# Increase the saturation by 50%hsv_image[..., 1] = np.clip(hsv_image[..., 1] * 1.5, 0, 255)# Increase the value (brightness) by 20%hsv_image[..., 2] = np.clip(hsv_image[..., 2] * 1.2, 0, 255)# Convert the image back to BGR color spacefiltered_image = cv2.cvtColor(hsv_image, cv2.COLOR_HSV2BGR)return filtered_image
# Load an example image
image = cv2.imread('image.jpg')
# Apply the colorful vibrant filter
filtered_image = colorful_vibrant_filter(image)
# Display the original and filtered images
cv2.imshow('Original Image', image)
cv2.imshow('Filtered Image', filtered_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
? ??灰度濾鏡
? ? 使用 Fotors 的“灰度”、“鍍鉻”和“黑白”選項,在幾秒鐘內將您的照片變成黑白色!“褪色白色”濾鏡還添加了微妙的仿舊效果。
import cv2
def grayscale_filter(image):"""Apply a grayscale filter to the input image.Args:image (numpy.ndarray): The input image.Returns:numpy.ndarray: The grayscale image."""# Convert the image to grayscale using cv2.cvtColorgrayscale_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)return grayscale_image
# Load an example image
image = cv2.imread('image.jpg')
# Apply the grayscale filter
grayscale_image = grayscale_filter(image)
# Display the original and grayscale images
cv2.imshow('Original Image', image)
cv2.imshow('Grayscale Image', grayscale_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
? ? 油畫濾鏡
? ? 厭倦了必須打開 Photoshop 才能為照片添加油畫濾鏡?只需在“油畫”下單擊幾下即可添加!“光澤”可讓所有東西都呈現出綠色,非常適合綠葉照片。
import cv2
# Load the image
img = cv2.imread('image.jpg')
# Apply oil painting filter
output = cv2.stylization(img, sigma_s=60, sigma_r=0.6)
# Display the output
cv2.imshow('Oil Painting', output)
cv2.waitKey(0)
cv2.destroyAllWindows()
? ? 這些圖像濾鏡提供了一種富有創意和藝術感的方式來增強和轉換您的圖像。使用 OpenCV 和 Python,用戶可以輕松應用這些濾鏡來創建各種時尚且具有視覺吸引力的轉換效果,從熱和卡通轉換到充滿活力的 VSCO 風格外觀和經典的灰度轉換。
二、MoveNet Lightning 和 CV 實現實時姿勢檢測
??在本文中,我們將探討如何使用 TensorFlow Lite 的 MoveNet Lightning 模型和 OpenCV 構建實時姿勢檢測系統。這個項目使我們能夠使用網絡攝像頭檢測身體關節并動態地可視化運動。?
????MoveNet Lightning 概述
??? MoveNet 是由 TensorFlow 開發的最先進的姿態估計模型,專為實時應用程序而設計。MoveNet 的 Lightning 變體針對速度和準確性進行了優化,使其適用于健身跟蹤、運動分析等任務。
????第 1 步:安裝所需的庫
????在開始之前,請確保您已安裝以下 Python 庫:
pip install tensorflow numpy opencv-python matplotlib
????這些庫對于加載 MoveNet 模型、處理視頻幀和可視化結果至關重要。
????第 2 步:加載 MoveNet 模型
????首先,我們將加載 TensorFlow Lite MoveNet Lightning 模型并分配張量進行推理。
import tensorflow as tf
import numpy as np
import cv2# Load the TensorFlow Lite model
interpreter = tf.lite.Interpreter(model_path='3.tflite')
interpreter.allocate_tensors()
????第 3 步:定義輔助函數
????為了可視化檢測到的姿勢,我們需要在每一幀上繪制關鍵點 (關節) 和連接 (骨骼)。
????繪制關鍵點
def draw_keypoints(frame, keypoints, confidence_threshold):"""Draws keypoints on the frame if their confidence exceeds the threshold."""y, x, c = frame.shapeshaped = np.squeeze(np.multiply(keypoints, [y, x, 1]))for kp in shaped:ky, kx, kp_conf = kpif kp_conf > confidence_threshold:cv2.circle(frame, (int(kx), int(ky)), 4, (0, 255, 0), -1)
????繪制連接
EDGES = {(0, 1): 'm', (0, 2): 'c', (1, 3): 'm', (2, 4): 'c',(0, 5): 'm', (0, 6): 'c', (5, 7): 'm', (7, 9): 'm',(6, 8): 'c', (8, 10): 'c', (5, 6): 'y', (5, 11): 'm',(6, 12): 'c', (11, 12): 'y', (11, 13): 'm', (13, 15): 'm',(12, 14): 'c', (14, 16): 'c'
}def draw_connections(frame, keypoints, edges, confidence_threshold):"""Draws connections (edges) between keypoints if both exceed the threshold."""y, x, c = frame.shapeshaped = np.squeeze(np.multiply(keypoints, [y, x, 1]))for edge, color in edges.items():p1, p2 = edgey1, x1, c1 = shaped[p1]y2, x2, c2 = shaped[p2]if (c1 > confidence_threshold) & (c2 > confidence_threshold):cv2.line(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
????第 4 步:實時姿勢檢測
????使用 OpenCV,我們將從網絡攝像頭捕獲幀,并通過 MoveNet 處理它們以進行姿勢檢測。
# Initialize webcam capture
cap = cv2.VideoCapture(1) # Use '0' for the default camerawhile cap.isOpened():ret, frame = cap.read()if not ret:break# Preprocess the frame for MoveNetimg = frame.copy()img = tf.image.resize_with_pad(np.expand_dims(img, axis=0), 192, 192)input_image = tf.cast(img, dtype=tf.float32)# Get input and output tensor detailsinput_details = interpreter.get_input_details()output_details = interpreter.get_output_details()# Run inferenceinterpreter.set_tensor(input_details[0]['index'], np.array(input_image))interpreter.invoke()keypoints_with_scores = interpreter.get_tensor(output_details[0]['index'])# Draw connections and keypoints on the framedraw_connections(frame, keypoints_with_scores, EDGES, 0.4)draw_keypoints(frame, keypoints_with_scores, 0.4)# Display the framecv2.imshow('MoveNet Lightning', frame)if cv2.waitKey(10) & 0xFF == ord('q'):breakcap.release()
cv2.destroyAllWindows()
? ? 如何運行
- 模型加載:TensorFlow Lite MoveNet 模型已加載并準備好進行推理。
- 幀預處理:每個網絡攝像頭幀的大小都會調整并填充,以匹配模型的預期輸入尺寸。
- 姿勢檢測:該模型預測每幀的關鍵點及其置信度分數。
- 可視化:關鍵點和連接疊加在框架上,實時動態更新。
????應用
????該項目具有多種應用:
- 健身追蹤和體型校正。
- 交互式系統的手勢識別。
- 運動中的實時運動分析。
????通過利用 TensorFlow Lite 的 MoveNet 和 OpenCV,我們創建了一個功能強大且高效的姿勢檢測系統。這種設置是輕量級的,非常適合邊緣設備上的實時應用程序。通過將該系統集成到健身或游戲應用程序中來進一步探索!
? ?源碼下載:
https://github.com/iamramzan/Real-Time-Pose-Detection-Using-MoveNet-Lightning-and-OpenCV
三、OpenCV修改一行代碼,將圖像匹配效果提升14%
OpenCV發布了4.5.1,包含了BEBLID算子,一個新的局部特征描述符,超越ORB。?
OpenCV 4.5.1中最令人興奮的特性之一是BEBLID (Boosted Efficient Binary Local Image Descriptor),一個新的描述符能夠提高圖像匹配精度,同時減少執行時間!這篇文章將向你展示這個魔法是如何實現的。所有的源代碼都在這個GitHub庫中:https://github.com/iago-suarez/beblid-opencv-demo/blob/main/demo.ipynb
在這個例子中,我們將匹配這兩個視角不一樣的圖像:
首先,確保安裝了正確的OpenCV版本是很重要的。在你喜歡的環境中,你可以通過以下方式安裝并檢查OpenCV Contrib版本:
pip install "opencv-contrib-python>=4.5.1"
python
>>> import cv2 as cv
>>> print(f"OpenCV Version: {cv.__version__}")
OpenCV Version: 4.5.1
在Python中加載這兩個圖像所需的代碼是:
import cv2 as cv# Load grayscale images
img1 = cv.imread("graf1.png", cv.IMREAD_GRAYSCALE)
img2 = cv.imread("graf3.png", cv.IMREAD_GRAYSCALE)if img1 is None or img2 is None:print('Could not open or find the images!')exit(0)
為了評估我們的圖像匹配程序,我們需要在兩幅圖像之間進行正確的(即ground truth)幾何變換。它是一個稱為單應性的3x3矩陣,當我們從第一個圖像中乘以一個點(在齊次坐標中)時,它返回第二個圖像中這個點的坐標。加載這個矩陣:
# Load homography (geometric transformation between image)
fs = cv.FileStorage("H1to3p.xml", cv.FILE_STORAGE_READ)
homography = fs.getFirstTopLevelNode().mat()
print(f"Homography from img1 to img2:\n{homography}")
下一步是檢測圖像中容易在其他圖像中找到的部分:Local image features。在本例中,我們將使用ORB,一個快速可靠的檢測器來檢測角點。ORB檢測到強角,在不同的尺度上比較它們,并使用FAST或Harris響應來挑選最好的。它還使用局部patch的一階矩來尋找每個角點的方向。我們檢測每個圖像中最多10000個角點:
detector = cv.ORB_create(10000)
kpts1 = detector.detect(img1, None)
kpts2 = detector.detect(img2, None)
在下面的圖片中,你可以看到500個用綠點標記的檢測響應最強的角點特征:
很好,現在是時候以一種我們可以在另一張圖中找到它們的方式來表示這些關鍵點了。這個步驟被稱為description,因為每個角點的局部patch中的紋理表示 為圖像上不同操作得到的數字的向量。有很多的描述符可以用,但如果我們想要一些精確的東西,即使在移動電話或低功耗設備上也能實時運行,OpenCV有兩個重要的方法:
- ORB(導向快速和旋轉簡短):一個經典的方法,有10年的歷史,工作相當好。
- BEBLID (Boosted Efficient Binary Local Image Descriptor):2020年引入的一個新的描述符,已被證明在幾個任務中改善了ORB。由于BEBLID適用于多種檢測方法,所以必須將ORB關鍵點的比例設置為0.75~1。
# Comment or uncomment to use ORB or BEBLID
descriptor = cv.xfeatures2d.BEBLID_create(0.75)
# descriptor = cv.ORB_create()
kpts1, desc1 = descriptor.compute(img1, kpts1)
kpts2, desc2 = descriptor.compute(img2, kpts2)
現在可以匹配這兩個圖像的描述符來建立對應關系了。讓我們使用暴力求解算法,它基本上比較了第一張圖像中的每個描述符和第二張圖像中的所有描述符。當我們處理二進制描述符時,使用漢明距離進行比較,即計算每對描述符之間不同的比特數。
這里還使用了一個叫做比率檢驗的小技巧。它不僅確保描述符1和2彼此相似,而且確保沒有其他像2一樣接近1的描述符。
matcher = cv.DescriptorMatcher_create(cv.DescriptorMatcher_BRUTEFORCE_HAMMING)
nn_matches = matcher.knnMatch(desc1, desc2, 2)
matched1 = []
matched2 = []
nn_match_ratio = 0.8 # Nearest neighbor matching ratio
for m, n in nn_matches:if m.distance < nn_match_ratio * n.distance:matched1.append(kpts1[m.queryIdx])matched2.append(kpts2[m.trainIdx])
因為我們知道正確的幾何變換,讓我們檢查有多少匹配是正確的(inliners)。如果圖像2中的點和從圖像1投射到圖像2的點距離小于2.5像素,我們認為匹配是有效的。
inliers1 = []
inliers2 = []
good_matches = []
inlier_threshold = 2.5 # Distance threshold to identify inliers with homography check
for i, m in enumerate(matched1):# Create the homogeneous pointcol = np.ones((3, 1), dtype=np.float64)col[0:2, 0] = m.pt# Project from image 1 to image 2col = np.dot(homography, col)col /= col[2, 0]# Calculate euclidean distancedist = sqrt(pow(col[0, 0] - matched2[i].pt[0], 2) + pow(col[1, 0] - matched2[i].pt[1], 2))if dist < inlier_threshold:good_matches.append(cv.DMatch(len(inliers1), len(inliers2), 0))inliers1.append(matched1[i])inliers2.append(matched2[i])
現在我們在inliers1和inliers2變量中有了正確的匹配,我們可以使用cv.drawMatches定性地評估結果。每一個對應點可以在更高級別的任務上對我們有幫助,比如homography estimation,Perspective-n-Point,?plane tracking,?real-time pose estimation?以及?images stitching。
由于很難定性地比較這種結果,讓我們繪制一些定量的評價指標。最能反映描述符可靠程度的指標是inlier的百分比:
Matching Results (BEBLID)
*******************************
# Keypoints 1: 9105
# Keypoints 2: 9927
# Matches: 660
# Inliers: 512
# Percentage of Inliers: 77.57%
使用BEBLID描述符獲得77.57%的inliers。如果我們在描述符部分注釋掉BEBLID并取消注釋ORB描述符,結果下降到63.20%:
# Comment or uncomment to use ORB or BEBLID
# descriptor = cv.xfeatures2d.BEBLID_create(0.75)
descriptor = cv.ORB_create()
kpts1, desc1 = descriptor.compute(img1, kpts1)
kpts2, desc2 = descriptor.compute(img2, kpts2)
Matching Results (ORB)
*******************************
# Keypoints 1: 9105
# Keypoints 2: 9927
# Matches: 780
# Inliers: 493
# Percentage of Inliers: 63.20%
總之,只需更改一行代碼,將ORB描述符替換為BEBLID ,就可以將這兩個圖像的匹配結果提高14%。這在需要局部特征匹配的高級任務中會產生很大影響,所以不要猶豫,試試BEBLID。
英文原文:??https://towardsdatascience.com/improving-your-image-matching-results-by-14-with-one-line-of-code-b72ae9ca2b73??