Python实现"位1的个数"的四种方法

给定一个无符号整数,返回该整数二进制表示中"1"的个数

Example 1:

Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011 

Example 2:

Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000

1:整数转二进制的基本方法,判断每一次求余数时余数是否为"1",是的话就累加

def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        sum = 0
        while n>0:
            res = n%2
            if res==1:
                sum += 1
            n = n//2
        return sum

2:bin()+count()方法(参考他人代码)

def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        return bin(n).count('1')

3:位运算(参考他人代码)

def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        sum = 0
        while n>0:
            sum += n&1
            n = n>>1
        return sum

4:模拟位运算(参考他人代码)

def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        sum = 0
        bit = 1
        while bit<=n:
            if bit&n>0:
                sum += 1
            bit *= 2
        return sum

算法题来自:https://leetcode-cn.com/problems/number-of-1-bits/description/

实现手势识别手指的个数,可以使用OpenCV-Python的图像处理和计算机视觉功能。以下是实现手势识别手指的个数的一般步骤: 1. 读取视频或摄像头捕捉的图像。 2. 对图像进行预处理,如去噪、二值化等。 3. 找到手部轮廓。 4. 检测手指。 5. 计算手指的个数。 下面是一个简单的代码示例,可以识别手掌并计算手指的个数: ```python import cv2 import numpy as np # 定义HSV颜色范围 lower_skin = np.array([0, 20, 70], dtype=np.uint8) upper_skin = np.array([20, 255, 255], dtype=np.uint8) cap = cv2.VideoCapture(0) while True: # 读取视频帧 ret, frame = cap.read() # 转换为HSV颜色空间 hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # 提取皮肤颜色区域 mask = cv2.inRange(hsv, lower_skin, upper_skin) # 去噪 mask = cv2.erode(mask, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2) # 找到轮廓 contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 找到最大轮廓 if len(contours) > 0: max_contour = max(contours, key=cv2.contourArea) # 找到凸包 hull = cv2.convexHull(max_contour, returnPoints=False) # 找到凸缺陷 defects = cv2.convexityDefects(max_contour, hull) # 计算手指的个数 finger_count = 0 if defects is not None: for i in range(defects.shape[0]): s, e, f, d = defects[i][0] start = tuple(max_contour[s][0]) end = tuple(max_contour[e][0]) far = tuple(max_contour[f][0]) # 计算手指长度 a = np.sqrt((end[0] - start[0])**2 + (end[1] - start[1])**2) b = np.sqrt((far[0] - start[0])**2 + (far[1] - start[1])**2) c = np.sqrt((end[0] - far[0])**2 + (end[1] - far[1])**2) angle = np.arccos((b**2 + c**2 - a**2) / (2*b*c)) # 如果角度小于90度,则为手指 if angle < np.pi/2: finger_count += 1 # 在图像上绘制手指个数 cv2.putText(frame, str(finger_count), (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA) # 显示结果 cv2.imshow('frame', frame) # 按下q键退出 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放视频捕获对象和销毁所有窗口 cap.release() cv2.destroyAllWindows() ``` 这个代码示例使用肤色检测和凸缺陷检测来识别手指的个数。检测到轮廓后,使用`cv2.convexHull`函数找到凸包,然后使用`cv2.convexityDefects`函数找到凸缺陷。对于每个凸缺陷,计算相应的角度,并将其视为手指。最后,在图像上绘制手指个数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值