根据元组将值插入像素

时间:2019-03-02 15:55:27

标签: python numpy opencv cv2

在下面的代码中,我想找到在阈值之后为黑色的所有像素,并将其转换为绿色。

import cv2
import numpy as np
import os

# Two readings of the image - color and gray
color_img = cv2.imread('myimage.jpg', cv2.IMREAD_COLOR)

gray_img = cv2.imread('myimage.jpg', cv2.IMREAD_GRAYSCALE)

# Perform threshold
ret, thresh = cv2.threshold(gray_img, 50, 255, cv2.THRESH_BINARY)

# Get indices of black pixels
indices = np.where(thresh == [0])

color = color_img.copy()

color[indices[0][:]][indices[1][:]][:] = [0, 255, 0]

cv2.imwrite('greens.jpg', color)

由于某些原因,像素保持原始值。为什么值保持不变?

1 个答案:

答案 0 :(得分:1)

您可以这样做:

#!/usr/bin/env python3

import cv2
import numpy as np

# Read image and make greyscale version - don't annoy disks by reading twice!
color = cv2.imread('image.jpg', cv2.IMREAD_COLOR)
gray  = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)

# Perform threshold
ret, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)

# Set all pixels in "color" to green where threshold is zero
color[(thresh==0)] = [0, 255, 0]

# Save result
cv2.imwrite('greens.jpg', color)

因此,如果您从这张图片开始:

enter image description here

您将获得此结果:

enter image description here