【问题标题】:Replace pixel color by size as a condition in an image按大小替换像素颜色作为图像中的条件
【发布时间】:2021-05-04 20:46:14
【问题描述】:

我有这张图片:

这是一个肉和平,我想测量大理石(白色部分)。为此,我使用了这个:

import numpy as np
import cv2

cv2.namedWindow('Image2', cv2.WINDOW_NORMAL)        # Create window with freedom of dimensions
cv2.resizeWindow('Image2', 600, 600)

def increase_brightness(img, value=30):
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)

    lim = 255 - value
    v[v > lim] = 0
    v[v <= lim] += value

    final_hsv = cv2.merge((h, s, v))
    return final_hsv

image = cv2.imread('image.jpeg')

image2 = increase_brightness(image)

lower_range=np.array([0, 155, 0])
upper_range=np.array([255,255,255])
mask=cv2.inRange(mask, lower_range, upper_range)

我得到了这张图片:

但最终图像中有噪点。有没有办法将最小的黑色像素替换为白色像素,例如使用像素大小作为条件?

或者有没有更好的方法来做到这一点?

【问题讨论】:

  • 使用 cv2.inRange() 对白色进行阈值处理,使图像的其余部分为黑色。

标签: python numpy opencv pixel mask


【解决方案1】:

这是使用 Python/OpenCV 的一种方法,即使用 cv2.inRange() 对白色进行阈值处理。

输入:

import cv2
import numpy as np

# load image
img = cv2.imread("meat.jpg")

# threshold on white
lower = (120,140,190)
upper = (255,255,255)

# create the mask and use it to change the colors
thresh = cv2.inRange(img, lower, upper)

# apply morphology to clean up small spots
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# count number of non-zero pixels
count = np.count_nonzero(thresh)

print("total white pixels =", count)

# write thresh to disk
cv2.imwrite("meat_thresh.png", thresh)

# display it
cv2.imshow("thresh", thresh)
cv2.waitKey(0)

文字信息:

总白色像素 = 41969

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 2012-09-30
    • 2010-12-05
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    相关资源
    最近更新 更多