python-3.x - 如何删除图像的某个部分?
问题描述
我有一张图片: 原始图片
我想删除图像的灰色网格部分而不影响图像的其余部分,即黑色圆圈内的部分。我为此写了一个代码
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()
使用此代码,我得到以下输出图像: 输出图像
但是,黑色圆圈内的一些像素也变成了白色,这不是我想要的。我想知道如何解决这个问题。
解决方案
您可以找到黑色圆圈的索引并将值分配给黑色圆圈左侧或右侧的像素。下面是这个的示例代码
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()
输入图像
输出图像
推荐阅读
- python - 如何在 Jupyter Notebook 中绘制假新闻中最常见的 30 个单词的条形图
- git - 在 Git 中撤消操作
- .net-core - 如何使 swagger 在 .net core web api 中使用自定义 swagger 文件而不是自动生成的文件
- css - 在 React 中居中 Formspree.io 输入字段
- c# - 如何在安装软件的多个文件夹中更新每个 xml 配置文件的 IP 地址
- python - Wikipedia LATITUDE 和 LONGITUDE 使用 XML XPATHS(在 Python 中)
- python - Python FFmpeg:单个静态图像加上音频输出海量文件大小
- python - 通过 python/kivy 的主文件夹 Android
- python - 如何在 github 操作上使用 Maven 构建并存储 python 输出
- python - 如何使用 pandas 加入 datetimeindex?