2/100. Hamming Distance

本文介绍了一种计算两个整数间汉明距离的高效方法,通过位运算符“^”进行异或操作,并利用bin()函数将结果转换为二进制形式,最后统计二进制字符串中‘1’的数量得到汉明距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
汉明距离即为二进制中相异位的个数,则测两个数的汉明距离,需先转为二进制,然后使用位运算符“^”(相异为1),最终统计“1”的个数即可。

class Solution:
    def hammingDistance(self, x, y):
        """
        :type x: int
        :type y: int
        :rtype: int
        """
        return(bin(x^y).count('1'))
                
  • 相关知识点:
    o. 位运算符“^”(异或):当两对应的二进位相异时,结果为1
    o. 十进制转二进制:bin()
#include <opencv2/opencv.hpp> #include <opencv2/features2d.hpp> #include <opencv2/calib3d.hpp> #include <iostream> using namespace cv; using namespace std; int main() { // 1. 加载左右图像 Mat imgLeft = imread("left.jpg"); Mat imgRight = imread("right.jpg"); if (imgLeft.empty() || imgRight.empty()) { cerr << "Error: Could not load image files!" << endl; return -1; } // 2. 检测特征点和计算描述子 Ptr<Feature2D> detector = ORB::create(); vector<KeyPoint> keypoints1, keypoints2; Mat descriptors1, descriptors2; detector->detectAndCompute(imgLeft, noArray(), keypoints1, descriptors1); detector->detectAndCompute(imgRight, noArray(), keypoints2, descriptors2); // 3. 特征匹配 Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create("BruteForce-Hamming"); vector<DMatch> matches; matcher->match(descriptors1, descriptors2, matches); // 4. 筛选优质匹配点 vector<DMatch> goodMatches; double minDist = 100, maxDist = 0; for (auto m : matches) { if (m.distance < minDist) minDist = m.distance; if (m.distance > maxDist) maxDist = m.distance; } for (auto m : matches) { if (m.distance <= max(2 * minDist, 30.0)) { goodMatches.push_back(m); } } // 5. 提取匹配点坐标 vector<Point2f> points1, points2; for (auto m : goodMatches) { points1.push_back(keypoints1[m.queryIdx].pt); points2.push_back(keypoints2[m.trainIdx].pt); } // 6. 计算基础矩阵F Mat F = findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99); // 7. 计算核线校正变换 Mat H1, H2; stereoRectifyUncalibrated(points1, points2, F, imgLeft.size(), H1, H2); // 8. 应用校正变换 Mat imgLeftRect, imgRightRect; warpPerspective(imgLeft, imgLeftRect, H1, imgLeft.size()); warpPerspective(imgRight, imgRightRect, H2, imgRight.size()); // 9. 显示结果 Mat canvas; hconcat(imgLeftRect, imgRightRect, canvas); // 绘制水平线验证核线对齐 for (int i = 0; i < canvas.rows; i += 30) { line(canvas, Point(0, i), Point(canvas.cols, i), Scalar(0, 255, 0), 1); } imshow("Rectified Images (Uncalibrated)", canvas); imwrite("rectified_uncalibrated.jpg", canvas); waitKey(0); return 0; }这个代码对吗
最新发布
07-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值