Python 3.x 如何删除图像的某一部分?
我有一个形象: 我想删除图像的灰色网格部分,而不影响图像的其余部分,即黑色圆圈内的部分。 我已经为此编写了一个代码Python 3.x 如何删除图像的某一部分?,python-3.x,image-processing,python-imaging-library,rgb,Python 3.x,Image Processing,Python Imaging Library,Rgb,我有一个形象: 我想删除图像的灰色网格部分,而不影响图像的其余部分,即黑色圆圈内的部分。 我已经为此编写了一个代码 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
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()
导入cv2
将numpy作为np导入
从PIL导入图像
imag=Image.open('results.jpg'))
imag.show()
pixelMap=imag.load()
img=Image.new(imag.mode,imag.size)
pixelsNew=img.load()
对于范围内的i(img.size[0]):
对于范围内的j(img.尺寸[1]):
如果((pixelMap[i,j]>(200,0,0))和(pixelMap[i,j]<(240,0,0)):
像素新[i,j]=(255255)
其他:
pixelsNew[i,j]=pixelMap[i,j]
img.show()
通过这段代码,我得到了以下输出图像:
但是,黑色圆圈内的一些像素也变为白色,这不是我想要的。我想知道如何解决这个问题。您可以找到黑圈的索引,并为黑圈左侧或右侧的像素赋值。下面是此应用程序的示例代码
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()
输入图像
输出图像