【问题标题】:Setting pixels values in OpenCV Python在 OpenCV Python 中设置像素值
【发布时间】:2018-12-12 13:49:35
【问题描述】:

改变像素值的速度有多快?在 C# 中,我只需要使用 GetPixel() 来获取像素值并使用 SetPixel() 来更改它(它很容易使用但速度很慢,MarshallCopy 和 Lock/UnlockBits 要快得多)。

在这段代码中,我将黑色像素标记为 1,将白色像素标记为 0

import tkFileDialog
import cv2
import numpy as np
from matplotlib import pyplot as plt

path = tkFileDialog.askopenfilename()
bmp = cv2.imread(path) #reading image
height, width, channels = bmp.shape

if channels == 3:
    bmp = cv2.cvtColor(bmp, cv2.COLOR_BGR2GRAY) #if image have 3 channels, convert to BW
    bmp = bmp.astype('uint8')

bmp = cv2.adaptiveThreshold(bmp,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv2.THRESH_BINARY,11,2) #Otsu thresholding

imageData = np.asarray(bmp) #get pixels values

pixelArray = [[0 for y in range(height)] for x in range(width)] #set size of array for pixels

for y in range(len(imageData)):
    for x in range(len(imageData[0])):
        if imageData[y][x] == 0:
            pixelArray[y][x] = 1 #if black pixels = 1
        else:
            pixelArray[y][x] = 0 #if white pixels = 0

在c#中,它可以是这样的:

for (y = 0; y < bmp.Height-1; y++)
            {
                for (x = 0; x < bmp.Width-1; x++)
                {
                    if (pixelArray[y, x] == 1)
                        newImage.SetPixel(x, y, Color.Black); //printing new bitmap
                    else
                        newImage.SetPixel(x, y, Color.White);
                }
            }
            image2.Source = Bitmap2BitmapImage(newImage);

在下一步中,我会将 countour 像素标记为“2”,但现在我想问你,如何根据我的特定值在 python 中设置新图像,然后显示它?出于实验目的,我只想按字节值反转图像(从 B&W 到 W&B)。你能帮我怎么做吗?

EDIT1

我想我找到了解决方案,但我有一个通道的 GREYSCALE 图像(我认为这就是我使用 cv2.cvtColor 将 3 通道图像转换为灰度图像时的工作原理)。函数如下:

im[np.where((im == [0,0,0]).all(axis = 2))] = [0,33,166]

可以很好地工作,但是如何使该功能适用​​于灰度图像?我想将一些黑色像素 (0) 设置为白色 (255)

【问题讨论】:

  • 如果黑色为 0,白色为 1,则可以使用 image=1-image 反转。如果黑色为 0,白色为 255,则可以使用 image=255-image 反转。
  • 感谢您的回复!但我不想简单地反转图像,而是根据我的pixelArray[][] 设置像素值,当“1” - 黑色时,当“0” - 白色时。我问这个问题是因为在下一步我会得到“2”作为计数,所以它会开始变得更复杂
  • 你可能想考虑一个LUT...stackoverflow.com/a/50598388/2836621
  • 我只是想实现 KMM 骨架算法,框图在这里imgur.com/a/zNq7D75
  • 我真的不需要 LUT,因为我只有两个像素值,白色 (255) 和黑色 (0)。 “1s”和“2s”是黑色,“0s”是白色在最后一步中,我将拥有(在pixelArray)值,例如 0、1 或 2。根据这个矩阵,我想设置每个像素(@987654332 @) 与 pixelArray 中的值相比(我删除标记为“2”的计数,因此“2”像素 == (255)

标签: python opencv


【解决方案1】:

对于单通道图像(灰度图像),请使用以下内容:

首先创建灰度图像的副本:

gray_2 = gray.copy()

现在将黑色像素指定为白色:

gray_2[np.where(gray == 0)] = 255

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    相关资源
    最近更新 更多