python 统计相同像素值个数

目录

[python 统计相同像素值个数](#python 统计相同像素值个数)

最大值附近的值


python 统计相同像素值个数

python 复制代码
import cv2
import numpy as np
import time
from collections import Counter

# 读取图像
image = cv2.imread('mask16.jpg')


# 将图像转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

area=gray_image.shape[0]*gray_image.shape[1]
print('shape',gray_image.shape)
# 将灰度图像展平为一维数组
pixels = gray_image.flatten()

start=time.time()
# 使用 Counter 统计每个像素值的出现次数
pixel_counts = Counter(pixels)

most_commons = pixel_counts.most_common(10)

print('time',time.time()-start)
count=0
for most_common in most_commons:
    count+=most_common[1]
    print(most_common,count,count/len(pixels))
print(count,count/len(pixels))
# 打印每个像素值及其出现次数
# for pixel_value, count in pixel_counts.items():
#     print(f"Pixel value {pixel_value}: {count} times")

最大值附近的值

python 复制代码
import cv2
import numpy as np
import time
from collections import Counter

# 读取图像
image = cv2.imread('mask16.jpg')


# 将图像转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

area=gray_image.shape[0]*gray_image.shape[1]
print('shape',gray_image.shape)
# 将灰度图像展平为一维数组
pixels = gray_image.flatten()

start=time.time()
# 使用 Counter 统计每个像素值的出现次数
pixel_counts = Counter(pixels)

most_commons = pixel_counts.most_common(10)

print('time',time.time()-start)
count=0
max_pixel=int(most_commons[0][0])
for ii, most_common in enumerate(most_commons):
    if abs(max_pixel- int(most_common[0]))<5:
        count+=most_common[1]
        print(most_common,count,count/len(pixels))
    else:
        print('ffffff',most_common[0])
print(count,count/len(pixels))
相关推荐
IVEN_2 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang4 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮4 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling4 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮7 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽7 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers