python-3.x - 如何删除图像的特定部分?

标签 python-3.x image-processing python-imaging-library rgb

我有一张图片: Original Image

我想删除图像的灰色网格部分而不影响图像的其余部分,即黑色圆圈内的部分。 我已经为此编写了代码

import cv2
import numpy as np
from PIL import Image
imag = Image.open('results.jpg')
imag.show()

pixelMap = imag.load()

img = Image.new( imag.mode, imag.size)
pixelsNew = img.load()

for i in range(img.size[0]):
    for j in range(img.size[1]):        
        if (( pixelMap[i,j]> (200,0,0)) and (pixelMap[i,j]< (240,0,0))):
            pixelsNew[i,j] = (255,255,255)
        else:
            pixelsNew[i,j] = pixelMap[i,j]
img.show()

使用这段代码,我得到了以下输出图像: Output Image

但是,黑色圆圈内的一些像素也变成了白色,这不是我想要的。我想知道如何解决这个问题。

最佳答案

您可以找到黑色圆圈的索引,并为黑色圆圈左侧或右侧的像素分配值。下面是这个的示例代码

import cv2
import numpy as np

# read the image
img = cv2.imread('original.png')
cv2.imshow("Image", img)

# convert image to numpy array and also to grayscale
img = np.array(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# get height and width of image
[rows, cols] = gray.shape

# now extract one row from image, find indices of black circle
# and make those pixels white which are to the left/right
# of black cirlce
for i in range(rows):
    row = gray[i, :] # extract row of image
    indices = np.where(row == 0)    # find indices of black circle
    indices = indices[0]

    # if indices are not empty
    if len(indices) > 0:
        # find starting/ending column index
        si = indices[0]
        ei = indices[len(indices)-1]

        # assign values to the range of pixels
        img[i, 0:si-1] = [255, 255, 255]
        img[i, ei+1:] = [255, 255, 255]
    # if indices is empty then make whole row white
    else:
        img[i,:] = [255, 255, 255]

cv2.imshow("Modified Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

输入图像

Input Image

输出图像

Output Image

关于python-3.x - 如何删除图像的特定部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55881270/

相关文章:

python - PyDICOM 无法读取像素数据,需要 GDCM 或 Pillow

python - 与水平内核卷积会产生奇怪的输出

python - 如何在不使用yaml.dump的情况下替换yaml文件中的字典值

python - 对齐打印的不同部分

python - 从 Uber Ludwig 中的图像发出训练模型

algorithm - 在图像上找到十字

python - 使用opencv识别浅灰色背景上的深灰色空心细胞

java - 使用 OpenCV 进行光学盲文识别

opencv - 在 Pillow/PIL中转换色彩空间

Python 3.5.1同目录下导入类