如何删除图像的特定部分? [英] How to delete a certain part of an Image?

查看:151
本文介绍了如何删除图像的特定部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张图片: 原始图片

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

I want to remove the grey mesh part of the image without affecting the rest of the image i.e., the part inside the black circle. I have written a code for that

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()

使用此代码,我得到以下输出图像: 输出图像

with this code I have got the following output image: Output Image

但是,黑色圆圈内的某些像素也更改为白色,这不是我想要的.我想知道如何解决这个问题.

But, Some of the pixels inside the black circle were also changed to white, which is not what I want. I would like to know how can this problem be solved.

推荐答案

您可以找到黑色圆圈的索引,并将值分配给黑色圆圈左侧或右侧的像素.下面是此示例代码

You can find the indices of black circle and assign values to the pixels that are either to the left or to the right of black circle. Below is the sample code for this

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()

输入图像

输出图像

这篇关于如何删除图像的特定部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆