CUDA C编程--HelloWorld


硬件平台: jetson nano

操作系统: Ubuntu 18.04

编译器版本: nvcc 10.2


例程:hello.cu

#include <stdio.h>

// 设备运行的代码
__global__ void foo()
{
    printf("Device: Hello CUDA!\r\n");
}

// 主程序
int main(int argc, char** argv)
{
    // 主机
    printf("Host:   Hello World!\r\n");
    // 调用设备执行的代码
    foo<<<1,1>>>();
    // 同步
    cudaDeviceSynchronize();

    return 0;
}

编译命令:

$ nvcc -o hello hello.cu

执行结果:

$ ./hello
Host:   Hello World!
Device: Hello CUDA!

- 阅读全文 -

AI视觉处理--运动物体检测


硬件平台:树莓派4B

工作流程:
读取图像-->灰度-->计算差值->开操作去除噪声(先侵蚀再膨胀)-->检测轮廓-->计算轮廓面积

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@功能描述: 运动识别
@实现方法: 计算两帧之间的差别,查找轮廓
@author: Alex.Duan
"""

import cv2
import numpy as np

# 载入图片
#img1 = cv2.imread("1.png")
#img2 = cv2.imread("2.png")
#cv2.imshow('img1',img1)
#cv2.imshow('img2',img2)

# 从摄像机读入图像
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480) 
ret, img2 = cap.read()
img1 = img2

while True:      
    ret, img2 = cap.read()
    # 转换为灰度图
    gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

    img1 = img2

    # 计算绝对差,并进行二值化(差值部分为白色)
    diff = cv2.absdiff(gray1, gray2);  
    reval,diff = cv2.threshold(diff, 45, 255, cv2.THRESH_BINARY)

    # 开操作(先侵蚀后膨胀)
    # 侵蚀: 去除干扰点, 5x5矩形核 
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    diff   = cv2.erode(diff,kernel)
    #cv2.imshow('erode',diff)
    # 膨胀: 11x11矩形核(侵蚀与膨胀均对白色部分)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (11, 11))
    diff   = cv2.dilate(diff,kernel)
    cv2.imshow('dilate',diff)

    # 查找轮廓
    image, contours, hierarchy = cv2.findContours(diff, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    
    # 计算轮廓面积
    area = 0
    for i in np.arange(len(contours)):
        area += cv2.contourArea(contours[i])

    # 通过轮廓面积大小来确定事件
    if area > 1000:
        print("Area is %f" %(area))

    # 绘制轮廓
    out = cv2.drawContours(img2, contours,-1, (0,255,0),thickness = 2)
    cv2.imshow('diff',out)
    #cv2.imshow('image',image)

    k = cv2.waitKey(10)
    if k == 27:
        break
# 关闭窗口
cv2.destroyAllWindows()

- 阅读全文 -

AI视觉处理--全景图像拼接


硬件平台:树莓派4B


拼接模块:Stitcher.py

import numpy as np
import cv2

class Stitcher:
    #----------------------------------------------------    
    # 拼接函数
    def stitch(self, images, ratio=0.75, reprojThresh=4.0, showMatches=False):
        # 获取输入图片
        (imageB, imageA) = images
        # 检测A、B图片的SIFT关键特征点,并计算特征描述子
        (kpsA, featuresA) = self.detectAndDescribe(imageA)
        (kpsB, featuresB) = self.detectAndDescribe(imageB)

        # 匹配两张图片的所有特征点,返回匹配结果
        M = self.matchKeypoints(kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh)
        # 如果没有匹配成功的特征点,退出算法
        if M is None:
            return None

        # 提取匹配结果:H是3x3视角变换矩阵      
        (matches, H, status) = M
        # 将图片A进行视角变换,result是变换后图片
        result = cv2.warpPerspective(imageA, H, (imageA.shape[1] + imageB.shape[1], imageA.shape[0]))
        #self.cv_show('result', result)
        # 将图片B传入result图片最左端
        result[0:imageB.shape[0], 0:imageB.shape[1]] = imageB
        #self.cv_show('result', result)
        # 检测是否需要显示图片匹配
        if showMatches:
            # 生成匹配图片
            vis = self.drawMatches(imageA, imageB, kpsA, kpsB, matches, status)
            # 返回结果
            return (result, vis)

        # 返回匹配结果
        return result
    #----------------------------------------------------     
    # 检测关键特征点,并计算特征描述子
    def detectAndDescribe(self, image):
        # 将彩色图片转换成灰度图
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 建立SIFT生成器
        descriptor = cv2.xfeatures2d.SIFT_create()

        # 检测SIFT特征点,并计算描述子
        (kps, features) = descriptor.detectAndCompute(gray, None)

        # (898,) (898, 128)
        # print(np.array(kps).shape, np.array(features).shape)  
        # <KeyPoint 000002062C605DE0>
        # print(kps[0])  
        # (3.369633913040161, 178.34132385253906)
        # print(kps[0].pt)  

        # 将结果转换成NumPy数组,并将kp转换成float32类型,便于接下来做计算。
        kps = np.float32([kp.pt for kp in kps])  # (898, 2)

        # 返回特征点集,及对应的描述特征
        return (kps, features)

    #----------------------------------------------------------------
    # 匹配两张图片的所有特征点,返回匹配结果
    def matchKeypoints(self, kpsA, kpsB, featuresA, featuresB, ratio, reprojThresh):
        # 建立暴力匹配器
        matcher = cv2.BFMatcher()
  
        # 使用KNN检测来自A、B图的SIFT特征匹配对,K=2
        rawMatches = matcher.knnMatch(featuresA, featuresB, 2)  # (898, 2)检测出每个点,匹配的2个点
        # 返回的M结果为[(1, 6), ..,(112, 113)]等等,里面的数字为第几个特征点
        matches = []
        for m in rawMatches:
            # 当最近距离跟次近距离的比值小于ratio值时,保留此匹配对
            if len(m) == 2 and m[0].distance < m[1].distance * ratio:
            # 存储两个点在featuresA, featuresB中的索引值
                matches.append((m[0].trainIdx, m[0].queryIdx))
        
        # 显示匹配列表(小括号中,后者为距离)
        # [(458, 16), (454, 18),...,(464, 25), (465, 26)]
        # print(matches)  

        # 当筛选后的匹配对数量大于4时,计算视角变换矩阵
        if len(matches) > 4:  # 实际计算出(148, 2)
            # 获取匹配对的点坐标(float32型)
            ptsA = np.float32([kpsA[i] for (_, i) in matches])
            print(ptsA.shape)  # (148, 2)
            ptsB = np.float32([kpsB[i] for (i, _) in matches])

            # 计算视角变换矩阵(把RANSAC和计算H矩阵合并到了一起)
            (H, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC, reprojThresh)
            # 该函数的作用就是先用RANSAC选择最优的四组配对点,再计算H矩阵。H为3*3矩阵
            print(status.shape)  # (148, 1)
            # 返回结果
            return (matches, H, status)

        # 如果匹配对小于4时,返回None
        return None

    def drawMatches(self, imageA, imageB, kpsA, kpsB, matches, status):
        # 初始化可视化图片,将A、B图左右连接到一起
        (hA, wA) = imageA.shape[:2]
        (hB, wB) = imageB.shape[:2]
        vis = np.zeros((max(hA, hB), wA + wB, 3), dtype="uint8")
        vis[0:hA, 0:wA] = imageA
        vis[0:hB, wA:]  = imageB

        # 联合遍历,画出匹配对
        for ((trainIdx, queryIdx), s) in zip(matches, status):
            # 当点对匹配成功时,画到可视化图上
            if s == 1:
                # 画出匹配对
                ptA = (int(kpsA[queryIdx][0]), int(kpsA[queryIdx][1]))
                ptB = (int(kpsB[trainIdx][0]) + wA, int(kpsB[trainIdx][1]))
                cv2.line(vis, ptA, ptB, (0, 255, 0), 1)

        # 返回可视化结果
        return vis

测试程序:ImageStitcher.py

from Stitcher import Stitcher
import cv2

# 读取拼接图片(注意图片左右的放置)
imageL = cv2.imread("2.jpg")    # 左
imageR = cv2.imread("1.jpg")    # 右,对右边的图形做变换    

# 把图片拼接成全景图
stitcher = Stitcher()
(result, vis) = stitcher.stitch([imageL, imageR], showMatches=True)

# 保存图片
# cv2.imwrite("3.png", vis)
# cv2.imwrite("4.png", result)

# 显示原图
#cv2.imshow("Right", imageR)
#cv2.imshow("Left" , imageL)
# 显示匹配图
#cv2.imshow("Keypoint Matches",  vis) 

# 显示合成结果
cv2.imshow("Result", result)        
cv2.waitKey(0)
cv2.destroyAllWindows()

安装必要的库:

$ sudo apt-get install libatlas-base-dev libjasper-dev
$ sudo apt-get install libqtgui4 libqttest4

否则会报以下错误:

ImportError: libcblas.so.3: cannot open shared object file: No such file or directory
ImportError: libjasper.so.1: cannot open shared object file: No such file or directory
ImportError: libQtGui.so.4: cannot open shared object file: No such file or directory
ImportError: libQtTest.so.4: cannot open shared object file: No such file or directory

问题描述: AttributeError: module 'cv2' has no attribute 'xfeatures2d'

解决方法:

sudo pip3 install opencv-contrib-python

问题描述: ImportError: /usr/local/lib/python3.7/dist-packages/cv2/cv2.cpython-37m-arm-linux-gnueabihf.so: undefined symbol: __atomic_fetch_add_8

解决方法:

LD_PRELOAD=/usr/lib/arm-linux-gnueabihf/libatomic.so.1

问题描述: This algorithm is patented and is excluded in this configuration; Set OPENCV_ENABLE_NONFREE CMake option and rebuild the library in function 'create'

解决方案: 采用低版本的库即可

$ pip3 install --user opencv-contrib-python==3.3.0.10

- 阅读全文 -

Linux应用笔记--deb包制作及apt源搭建


操作系统: raspbian/debian

制作如下目录及文件

mydeb    
|----DEBIAN
   |------- control           (描述文件)
   |------- postinst          (安装后执行有脚本)
   |------- postrm            (卸载时执行的脚本)
|---- usr/local/bin               
   |----- helloworld.sh       (待安装的文件)
|---- lib/systemd/system               
   |----- helloworld.service  (启动服务,可选)

control文件 内容如下:

Package: helloworld
Version: 1.0                
Section: free             
Prioritt: optional        
Architecture: armhf      
Maintainer: admin@oroct.com        
Description: make deb package example

postinst文件: 软件安装后执行的脚本(可选)

# !/bin/sh
echo "install mydeb" >> /var/log/mydeb.log

postrm文件:软件删除后执行的脚本(可选)

# !/bin/sh
echo "remove mydeb" >> /var/log/mydeb.log

生成deb安装包: 第一个参数为将要打包的目录名,第二个参数为生成包的名称

$ dpkg -b mydeb mydeb.deb

安装测试:

$ dpkg -i  mydeb.deb

删除测试:

$ dpkg -r  mydeb.deb

一键创建相关文件脚本:

#!/bin/sh
PKGNAME=helloworld 
VERSION=1.0

# 创建相关目录
if [ ! -d DEBIAN ] ; then 
    mkdir DEBIAN 
fi
if [ ! -d usr/local/bin ] ; then 
    mkdir -p usr/local/bin
fi
if [ ! -d lib/systemd/system ] ; then 
    mkdir -p lib/systemd/system
fi

# 创建相关文件
echo "#!/bin/sh" > DEBIAN/postinst
echo "systemctl enable ${PKGNAME}.service" >> DEBIAN/postinst
echo "systemctl start ${PKGNAME}.service"  >> DEBIAN/postinst

echo "#!/bin/sh" > DEBIAN/postrm
echo "systemctl stop ${PKGNAME}.service"    >> DEBIAN/postrm
echo "systemctl disable ${PKGNAME}.service" >> DEBIAN/postrm

echo "Package: ${PKGNAME}"   > DEBIAN/control
echo "Version: ${VERSION}"  >> DEBIAN/control               
echo "Section: free "       >> DEBIAN/control            
echo "Prioritt: optional"   >> DEBIAN/control       
echo "Architecture: armhf"  >> DEBIAN/control     
echo "Maintainer: admin@oroct.com" >> DEBIAN/control      
echo "Description: " >> DEBIAN/control

https://www.cnblogs.com/xiang--liu/p/12994429.html

- 阅读全文 -

Jetson Nano笔记--VNC


文章摘要: 解决了不接显示屏时VNC黑屏的问题


硬件平台:Jetson Nano
操作系统:Ubuntu 18.04


安装vino:

sudo apt install vino

配置VNC server:

gsettings set org.gnome.Vino prompt-enabled false
gsettings set org.gnome.Vino require-encryption false

设置enabled参数: /usr/share/glib-2.0/schemas/org.gnome.Vino.gschema.xml

<key name='enabled' type='b'>
  <summary>Enable remote access to the desktop</summary>
  <description>
    If true, allows remote access to the desktop via the RFB
    protocol. Users on remote machines may then connect to the
    desktop using a VNC viewer.
  </description>
  <default>false</default>
</key>

设置为Gnome模式:

sudo glib-compile-schemas /usr/share/glib-2.0/schemas

设置VNC登陆密码: 123456

$ gsettings set org.gnome.Vino authentication-methods "['vnc']"
$ gsettings set org.gnome.Vino vnc-password $(echo -n '123456'|base64)

设置开机自启动VNC

gsettings set org.gnome.Vino enabled true

设置自动启动脚本:
在~/.config/autostart或者/etc//autostart中新建文件vino-server.desktop

[Desktop Entry]
Type=Application
Name=Vino VNC server
Exec=/usr/lib/vino/vino-server
NoDisplay=true

注意事项: 必须在autostart中启动,而不能在systemd中启动。


设置用户自动登陆:
修改/etc/gdm3/custom.conf文件

[daemon]
# Enabling automatic login
AutomaticLoginEnable = true
AutomaticLogin = nvidia

- 阅读全文 -


Copyright©2025 春天花会开, All Rights Reserved. Email: webmaster@oroct.com