如何计算图像中不规则物体的面积(opencv)?

2023-12-13

So I have this image: enter image description here

我需要计算特定部分的面积,所以我编写了以下代码:

# packages
from imutils import perspective
from imutils import contours
import numpy as np
import imutils
import cv2

image = cv2.imread('image1.jpg')

# load the image, convert it to grayscale, and blur it slightly
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
edged = cv2.Canny(gray, 80, 150)
edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)
# find contours
cnts = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
# sort the contours from left-to-right and initialize the
(cnts, _) = contours.sort_contours(cnts)
pixelsPerMetric = None
# draw the necessary contour
cv2.drawContours(image, max(cnts, key=cv2.contourArea), -1, (0, 0, 255), 5)
cv2.imshow("Image", image)
cv2.waitKey(0)

And I obtained this image: enter image description here

我想测量红色轮廓的面积(mm²)。作为参考,我有硬币(572.55 毫米),还有其他问题。是否可以测量红色轮廓内的红色和黑色比例。一些建议。


我会这样走。本质上:

  • 在第一部分中,您将处理外部轮廓:您将找到硬币和切片的外部边框

external borders

  • 硬币面积将帮助您测量整个切片的面积(以 cm^2 为单位),如果您想要以 mm^2 为单位,则可以将该值乘以 100
  • 那时你只需要量化切片的瘦肉部分,其灵感来自这个很棒的片段 and fmw42上面的评论很棒

lean selection

  • 切片的脂肪部分可以通过差异找到,即用我的值我得到57.71%切片是瘦的,所以剩下的42.29% is fat
  • 如果您不想要像此片段中那样的整个瘦肉部分,只需计算红色轮廓的面积,您似乎已经准备好这样做:请记住,切片会比我在这里计算的更胖

废话不多说,代码如下:

import cv2
import numpy as np
import math

# input image
path = "image1.jpg"
# 1 EUR coin diameter in cm
coinDiameter = 2.325
# real area for the coin in cm^2
coinArea = (coinDiameter/2)**2 * math.pi
# initializing the multiplying factor for real size
realAreaPerPixel = 1


# pixel to cm^2
def pixelToArea(objectSizeInPixel, coinSizeInPixel):
    # how many cm^2 per pixel?
    realAreaPerPixel = coinArea / coinSizeInPixel
    print("realAreaPerPixel: ", realAreaPerPixel)
    # object area in cm^2
    objectArea = realAreaPerPixel * objectSizeInPixel
    return objectArea    


# finding coin and steak contours
def getContours(img, imgContour):
    
    # find all the contours from the B&W image
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    # needed to filter only our contours of interest
    finalContours = []
    
    # for each contour found
    for cnt in contours:
        # cv2.drawContours(imgContour, cnt, -1, (255, 0, 255), 2)
        # find its area in pixel
        area = cv2.contourArea(cnt)
        print("Detected Contour with Area: ", area)

        # minimum area value is to be fixed as the one that leaves the coin as the small object on the scene
        if (area > 5000):
            perimeter = cv2.arcLength(cnt, True)
            
            # smaller epsilon -> more vertices detected [= more precision]
            epsilon = 0.002*perimeter
            # check how many vertices         
            approx = cv2.approxPolyDP(cnt, epsilon, True)
            #print(len(approx))
            
            finalContours.append([len(approx), area, approx, cnt])

    # we want only two objects here: the coin and the meat slice
    print("---\nFinal number of External Contours: ", len(finalContours))
    # so at this point finalContours should have only two elements
    # sorting in ascending order depending on the area
    finalContours = sorted(finalContours, key = lambda x:x[1], reverse=False)
    
    # drawing contours for the final objects
    for con in finalContours:
        cv2.drawContours(imgContour, con[3], -1, (0, 0, 255), 3)

    return imgContour, finalContours

    
# sourcing the input image
img = cv2.imread(path)
cv2.imshow("Starting image", img)
cv2.waitKey()

# blurring
imgBlur = cv2.GaussianBlur(img, (7, 7), 1)
# graying
imgGray = cv2.cvtColor(imgBlur, cv2.COLOR_BGR2GRAY)
# canny
imgCanny = cv2.Canny(imgGray, 255, 195)

kernel = np.ones((2, 2))
imgDil = cv2.dilate(imgCanny, kernel, iterations = 3)
# cv2.imshow("Diluted", imgDil)
imgThre = cv2.erode(imgDil, kernel, iterations = 3)

imgFinalContours, finalContours = getContours(imgThre, img)

# first final contour has the area of the coin in pixel
coinPixelArea = finalContours[0][1]
print("Coin Area in pixel", coinPixelArea)
# second final contour has the area of the meat slice in pixel
slicePixelArea = finalContours[1][1]
print("Entire Slice Area in pixel", slicePixelArea)

# let's go cm^2
print("Coin Area in cm^2:", coinArea)
print("Entire Slice Area in cm^2:", pixelToArea(slicePixelArea, coinPixelArea))

# show  the contours on the unfiltered starting image
cv2.imshow("Final External Contours", imgFinalContours)
cv2.waitKey()


# now let's detect and quantify the lean part

# convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 
# set lower and upper color limits
lowerVal = np.array([0, 159, 160])
upperVal = np.array([101, 255, 253])
# Threshold the HSV image to get only red colors
mask = cv2.inRange(hsv, lowerVal, upperVal)
# apply mask to original image - this shows the red with black blackground
final = cv2.bitwise_and(img, img, mask= mask)

# show selection
cv2.imshow("Lean Cut", final)
cv2.waitKey()

# convert it to grayscale because countNonZero() wants 1 channel images
gray = cv2.cvtColor(final, cv2.COLOR_BGR2GRAY)
# cv2.imshow("Gray", gray)
# cv2.waitKey()
meatyPixelArea = cv2.countNonZero(gray)

print("Red Area in pixel: ", meatyPixelArea)
print("Red Area in cm^2: ", pixelToArea(meatyPixelArea, coinPixelArea))

# finally the body-fat ratio calculation
print("Body-Fat Ratio: ", meatyPixelArea/slicePixelArea*100, "%")

cv2.destroyAllWindows()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何计算图像中不规则物体的面积(opencv)? 的相关文章

  • 在 Python 中使用 XPath 和 LXML

    我有一个 python 脚本 用于解析 XML 并将某些感兴趣的元素导出到 csv 文件中 我现在尝试更改脚本以允许根据条件过滤 XML 文件 等效的 XPath 查询将是 DC Events Confirmation contains T
  • 是否有一个类可以获取应用程序中的默认图片查看器?

    我不想访问 iPhone 上的图像 我想显示我的应用程序中的图像 但就像您查看 iPhone 相册中的图片一样 使用所有捏合和缩放控件等 这可能吗 我认为可能 偶然 有像 AVMediaPlayer 类这样的类可以做到这一点 谢谢 汤姆 如
  • Python 中的六边形自组织映射

    我在寻找六边形 自组织映射 http en wikipedia org wiki Self organizing map在Python上 准备好模块 如果存在的话 绘制六边形单元格的方法 将六边形单元作为数组或其他方式使用的算法 About
  • Python 中 genfromtxt() 的可变列数?

    我有一个 txt具有不同长度的行的文件 每一行都是代表一条轨迹的一系列点 由于每条轨迹都有自己的长度 因此各行的长度都不同 也就是说 列数从一行到另一行不同 据我所知 genfromtxt Python 中的模块要求列数相同 gt gt g
  • python ttk treeview:如何选择并设置焦点在一行上?

    我有一个 ttk Treeview 小部件 其中包含一些数据行 如何设置焦点并选择 突出显示 指定项目 tree focus set 什么也没做 tree selection set 0 抱怨 尽管小部件明显填充了超过零个项目 但未找到项目
  • python中函数变量的作用域

    假设我们有两个函数 def ftpConnect ftp FTP server ftp login ftp cwd path def getFileList ftpConnect files ftp nlst print files 如果我
  • 将 subprocess.Popen 的输出通过管道传输到文件

    我需要启动一些长时间运行的进程subprocess Popen 并希望拥有stdout and stderr从每个自动管道到单独的日志文件 每个进程将同时运行几分钟 我想要两个日志文件 stdout and stderr 每个进程当进程运行
  • 如何在 Windows 上使用 Python 3.6 来安装 Python 2.7

    我想问一下如何使用pip install对于 Python 2 7 当我之前安装并使用 Python 3 6 时 我现在必须使用 Windows 上的 Python 版本 pip install 继续安装 Python 3 6 我需要使用以
  • 行为:如何从另一个文件导入步骤?

    我刚刚开始使用behave http pythonhosted org behave 一个Pythonic BDD框架 使用小黄瓜语法 http docs behat org guides 1 gherkin html 行为需要一个特征 例
  • 使用 genfromtxt 导入 numpy 中缺失值的 csv 数据

    我有一个 csv 文件 看起来像这样 实际文件有更多的列和行 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 假设文件的名称是info csv如果我尝试使用导入它 data numpy genfromtxt i
  • Python 中的这种赋值方式叫什么? a = b = 真

    我知道关于元组拆包 http docs python org tutorial datastructures html tuples and sequences但是当一行中有多个等号时 这个赋值被称为什么 阿拉a b True 它总是让我有
  • 在wxpython中使用wx.TextCtrl并在按钮单击后显示数据的简单示例 - wx新手

    我正在学习 python 并尝试使用 wxpython 进行 UI 开发 也没有 UI exp 我已经能够创建一个带有面板 按钮和文本输入框的框架 我希望能够在文本框中输入文本 并让程序在单击按钮后对输入框中的文本执行操作 我可以获得一些关
  • 在 Mac 上安装 Pygame 到 Enthought 构建中

    关于在 Mac 上安装 Pygame 有许多未解答的问题 但我将在这里提出我的具体问题并希望得到答案 我在 Mac 上安装 Pygame 时遇到了难以置信的困难 我使用 Enthought 版本 EPD 7 3 2 32 位 它是我的默认框
  • 使用循环将对象添加到列表(python)

    我正在尝试使用 while 循环将对象添加到列表中 基本上这就是我想做的 class x pass choice raw input pick what you want to do while choice 0 if choice 1 E
  • 如何逐像素绘制正方形(Python,PIL)

    在空白画布上 我想使用 Pillow 逐像素绘制一个正方形 我尝试使用 img putpixel 30 60 155 155 55 绘制一个像素 但它没有执行任何操作 from PIL import Image def newImg img
  • WindowsError:[错误 5] 访问被拒绝

    我一直在尝试终止一个进程 但我的所有选项都给出了 Windows 访问被拒绝错误 我通过以下方式打开进程 一个python脚本 test subprocess Popen sys executable testsc py 我想杀死那个进程
  • 是否可以写一个负的python类型注释

    这可能听起来不合理 但现在我需要否定类型注释 我的意思是这样的 an int Not Iterable a string Iterable 这是因为我为一个函数编写了一个重载 而 mypy 不理解我 我的功能看起来像这样 overload
  • Pandas 在特定列将数据帧拆分为两个数据帧

    I have pandas我组成的 DataFrameconcat 一行由 96 个值组成 我想将 DataFrame 从值 72 中分离出来 这样 一行的前 72 个值存储在 Dataframe1 中 接下来的 24 个值存储在 Data
  • 如何对字符串列表进行排序?

    在 Python 中创建按字母顺序排序的列表的最佳方法是什么 基本回答 mylist b C A mylist sort 这会修改您的原始列表 即就地排序 要获取列表的排序副本而不更改原始列表 请使用sorted http docs pyt
  • 在什么情况下,使用 HTTP/2 单独加载图像会比使用 HTTP/1.1 中的精灵一次加载所有图像慢?

    HTTP 2 使多路复用连接成为可能 从而消除了与服务器的多个连接的需要 通过单个连接 可以将许多单独的图像发送到客户端 这避免了将多个图像组合成一个并使用 CSS 将其分开的旧图像精灵模式 我很好奇精灵在 HTTP 2 世界中是否仍然会更

随机推荐

  • Javascript - 通过键值从数组中删除对象

    我有一个对象数组 let people Name Bob Age 45 Name Jim Age 45 let person people filter person gt person Name Bob 这会返回 Bob 但我如何删除他呢
  • 根据值将一列转换为多列

    In Python I am wondering if there is a way to transform a one column dataframe from this 进入这个 来源DF In 204 df Out 204 Cou
  • R 在 Lime 上解释 - 存储在“object”和“newdata”中的特征名称不同

    您好 我正在研究在 LIME 模型上使用 R 解释 当我运行这部分时一切都很好 Library library tm library SnowballC library caTools library RWeka library caret
  • 将 localStorage 值获取到 php [重复]

    这个问题在这里已经有答案了 我在 localStorage 中设置了一个变量 我想将它放入 php 中 当php执行时 该值已经在本地存储中设置 但是我应该如何进入php 我尝试过这样的事情 myvar 但这由于某些原因给出了Uncaugh
  • 当传递给函数时,如何强制警告使用错误大小的数组?

    假设您有一个以字符串作为参数的函数 void foo char arg 如果我们确定数组 不要与字符串长度混淆 谢谢 chux 将始终具有一定的大小 假设为 8 那么我们可以这样做 void bar char arg 8 然后这样称呼它 c
  • 聚合物 3 - 谷歌地图

    我想知道如何将 Google 地图包含在 Polymer 3 中 我刚刚从 Polymer 2 升级到 Polymer 3 这是我的示例 不是入门套件的工作基础 import PolymerElement html from polymer
  • 构建 QGIS 时未解析的符号

    我已经能够从这一步取得进展 在 Windows 7 上构建 QGIS 源代码 不工作 我正在尝试使用 Visual Studio 10 Express 构建最新的 QGIS 2 10 1 但在构建 ALL BUILD 时获取这些未解析的符号
  • 我在每个工作表的 VBA 循环中搞砸了什么?

    目前 我必须一次发送多封信件 并且通常只替换单元格中的一两个单词 问题是我需要将这些单词加粗 并且在 150 个工作表上单独使用这个宏会很乏味 我对编码非常陌生 并尝试在线搜索以编辑此代码以循环所有工作表 但我尝试的所有操作似乎只会更改我所
  • 频繁地在 ObjectOutputStream 上调用 reset() 可以吗?

    我读过一些让我不确定并寻找替代方法的地方 是否打电话reset 太频繁会导致网络紧张 还是不必要的 我正在使用 TCP 通过 ObjectOutputStream 发送对象 对象值在再次写入之前会发生更改 现在相同的对象但包含不同的值 没有
  • Spring boot - 发生非法反射访问操作

    我向演示应用程序添加了两个新的依赖项 即 spring 集成和 spring 集成文件 之后我在控制台中收到以下警告 应用程序工作正常 但它困扰着我 我怎样才能克服这个问题 WARNING Illegal reflective access
  • 使用向左和向右箭头键选择上一个/下一个菜单而不是下一个/上一个菜单

    在完整的应用程序中注意到 但在简单的演示中可以完全重现 我有一个MenuStrip包含三个菜单 A B and C 每个菜单包含三个项目 A1 A2 C2 C3 When I press Alt the first menu A becom
  • 如何在javascript中比较两个日期时间?

    我尝试通过 C 的 JSON 解析创建标记 我有一个关于 javascript 中的日期时间比较的小问题 var nowDate new Date var LastTenMin new Date nowDate getFullYear no
  • 尝试运行工作表更改事件两次

    我正在尝试为两个不同的列 A 和 I 运行此工作表更改事件 Private Sub Worksheet Change ByVal Target As Range Dim A As Range B As Range Inte As Range
  • 在哪里可以找到 iPhone 系统按钮和图标图形?

    我正在尝试找到一种在网站中使用原始 Apple 系统按钮和图标的方法 有没有办法把这些原始图形变成png格式 当然 获得它们的方法并不太好 我想到的有两个 将他们从这个链接 然后转换为png 在 iPhone 上截取屏幕截图 然后从保存的图
  • 将材料 UI 选项卡与 React 一起使用

    我偶然发现的是了解如何使用 Material UI 选项卡 我发现了很多帖子 但每个帖子都针对不同版本的材料 UI 并且每个帖子都给出了完全不同的实现方式 我创建的 Web 应用程序是一个分析仪表板 我的页面上有 3 个部分 应用栏 主体
  • 在Python中声明静态方法是否需要@staticmethod装饰器?

    我很好奇为什么我们需要 staticmethod装饰器将方法声明为静态 我正在阅读有关 Python 中的静态方法的内容 并且我了解到静态方法可以在不实例化其类的情况下进行调用 所以我尝试了下面的两个示例 但两者的作用相同 class St
  • 尝试使用 Dagger2 了解 Android 上的依赖注入

    我有以下代码工作 某类 public class SomeClass Inject Named special OkHttpClient mOkHttpClient public SomeClass Activity activity My
  • 访问模型中的设备 current_user

    您好 我正在尝试访问模型中的 current user 以便使用 find or create by 动态创建元素 以下是我的模型中的方法 def opponent name name self opponent Opponent find
  • Android JNI:32 位与 64 位设备的兼容性?

    我有一些使用本机组件的库 这些库是使用 NDK 为 32 位 Arm 架构构建的 现在我们在现代设备上拥有 64 位处理器 所以我想知道这些库是否可以工作 在我的情况下 我没有本机库的源代码文件 只有 SO 文件 我无法为 64 位构建它们
  • 如何计算图像中不规则物体的面积(opencv)?

    So I have this image 我需要计算特定部分的面积 所以我编写了以下代码 packages from imutils import perspective from imutils import contours impor