51c视觉~CV~合集10

server/2025/2/5 13:52:17/

我自己的原文哦~    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​​


http://www.ppmy.cn/server/165156.html

相关文章

【生成模型之十三】SmartEraser

论文&#xff1a;SmartEraser: Remove Anything from Images using Masked-Region Guidance 代码&#xff1a; https://github.com/longtaojiang/SmartEraser 类型&#xff1a;fine-tuned diffusion model 其他&#xff1a;支持简历修改面试辅导 一、背景 到目前为止&#…

1. 【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--前言

在我们的专栏《单体开发》中&#xff0c;我们实现了一个简单的记账软件的服务端&#xff0c;并且成功上线。随着用户数量的不断增长&#xff0c;问题逐渐开始显现。访问量逐渐增加&#xff0c;服务端的压力也随之加大。随着访问量的攀升&#xff0c;服务端的响应时间变得越来越…

【C语言篇】“三子棋”

一、游戏介绍 三子棋&#xff0c;英文名为 Tic - Tac - Toe&#xff0c;是一款简单而经典的棋类游戏。游戏在一个 33 的棋盘上进行&#xff0c;两名玩家轮流在棋盘的空位上放置自己的棋子&#xff08;通常用 * 和 # 表示&#xff09;&#xff0c;率先在横、竖或斜方向上连成三个…

【华为OD-E卷 - 最大矩阵和 100分(python、java、c++、js、c)】

【华为OD-E卷 - 最大矩阵和 100分&#xff08;python、java、c、js、c&#xff09;】 题目 给定一个二维整数矩阵&#xff0c;要在这个矩阵中选出一个子矩阵&#xff0c;使得这个子矩阵内所有的数字和尽量大&#xff0c;我们把这个子矩阵称为和最大子矩阵&#xff0c;子矩阵的…

搜索引擎友好:设计快速收录的网站架构

本文来自&#xff1a;百万收录网 原文链接&#xff1a;https://www.baiwanshoulu.com/14.html 为了设计一个搜索引擎友好的网站架构&#xff0c;以实现快速收录&#xff0c;可以从以下几个方面入手&#xff1a; 一、清晰的目录结构与层级 合理划分内容&#xff1a;目录结构应…

计算机网络 IP 网络层 2 (重置版)

IP的简介&#xff1a; IP 地址是互联网协议地址&#xff08;Internet Protocol Address&#xff09;的简称&#xff0c;是分配给连接到互联网的设备的唯一标识符&#xff0c;用于在网络中定位和通信。 IP编制的历史阶段&#xff1a; 1&#xff0c;分类的IP地址&#xff1a; …

Brave132 编译指南 Windows 篇:配置 Git(四)

1. 引言 在 Brave 浏览器 132 版本的开发流程中&#xff0c;Git 作为核心的版本控制工具&#xff0c;发挥着至关重要的作用。作为业界主流的分布式版本控制系统&#xff0c;Git 为开发者提供了强大的源代码管理能力。借助 Git&#xff0c;您可以轻松追踪代码的每一次变更、管理…

解决国内服务器 npm install 卡住的问题

在使用国内云服务器时&#xff0c;经常会遇到 npm install 命令执行卡住的情况。本文将分享一个典型案例以及常见的解决方案。 问题描述 在执行以下命令时&#xff1a; mkdir test-npm cd test-npm npm init -y npm install lodash --verbose安装过程会卡在这个状态&#xf…