简体   繁体   English

如何在 python 中裁剪 PNG 图像?

[英]How do you crop a PNG image in python?

I have successfully managed to extract a skin patch from a facial image.我已经成功地从面部图像中提取了皮肤贴片。 However;然而; for my task, I don't need the bottom eye and eyelash part.对于我的任务,我不需要底部的眼睛和睫毛部分。 Is there a way to crop the following png image from the top at a slight angle?有没有办法从顶部以一个小角度裁剪以下 png 图像? The resultant image should be in PNG format.生成的图像应为 PNG 格式。 I want to crop the following original image to the desired image:我想将以下原始图像裁剪为所需的图像:

Original Image原始图像

Desired Image所需图像

As long as you have the color values of the line of which you want to crop above of, you can do something like this:只要您有要在其上方裁剪的线条的颜色值,就可以执行以下操作:

import cv2
import numpy as np

img = cv2.imread("image.png")

for i, j in zip(*np.where(np.all(img == [0, 0, 253], 2))):
    img[:i, j] = 0

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

Output: Output:

在此处输入图像描述

Explanation:解释:

  1. Import the necessary libraries:导入必要的库:
import cv2
import numpy as np
  1. Read in the image:读入图片:
img = cv2.imread("image.png")
  1. Loop though the indices of the image where the BGR value of the pixel at the indices is the BGR value of the line's color:循环遍历图像的索引,其中索引处像素的 BGR 值是线条颜色的 BGR 值:
for i, j in zip(*np.where(np.all(img == [0, 0, 253], 2))):
  1. Set all the pixels before the outer index at the inner index to black.将内部索引处外部索引之前的所有像素设置为黑色。 If you were to visualize it it would be drawing black vertical lines one by one:如果您要对其进行可视化,它将是一条一条地绘制黑色垂直线:
    img[:i, j] = 0
  1. Show the resulting image:显示生成的图像:
cv2.imshow("Image", img)
cv2.waitKey(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 中裁剪 SVG 图像? - How can you crop an SVG Image in Python? 你如何在discord.py中用枕头将图像裁剪成圆形? - How do you crop an image to be circular with pillow in discord.py? 如何使用python窗口将屏幕的可裁剪png图像保存到桌面? - How do you save a croppable png image of your screen to your desktop using python windows? 使用我自己的cothon与python和PIL裁剪透明的PNG图像 - Crop transparent PNG image with my own coords with python and PIL 如何在Python中使用OpenCV裁剪图像的黑色背景? - How do I crop the black background of the image using OpenCV in Python? 如何根据 python 中的自定义蒙版裁剪图像? - How do I crop an image based on custom mask in python? 如何使用python在白色背景上裁剪图像? - How do I crop an image on a white background with python? 如何从边界框裁剪图像并为每个框创建新图像 - How do you crop an image from bounding box and create new image for each box 如何将自定义信息保存到 Python 中的 PNG 图像文件? - How do I save custom information to a PNG Image file in Python? 给定要裁剪的四个角的坐标,如何裁剪图像 - How do I crop an image given the coordinates of the four corners to crop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM