如何计算图像中不规则物体的面积(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)? 的相关文章

随机推荐

  • 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