简体   繁体   English

从图像中复制黑色像素并粘贴到具有偏移的同一图像中

[英]Copy black pixels from image and paste in same image with offset

在此处输入图像描述 I've been trying to get some masking to work in my pictures, but I guess there has to be an easier way to do this:我一直在尝试在我的图片中添加一些遮罩,但我想必须有一种更简单的方法来做到这一点:

a) I have an BW picture (photo) showing numbers from a display, "test.png" ( 1000x300 px) a) 我有一张 BW 图片(照片),显示来自显示器的数字,“test.png”(1000x300 像素)

b) I want to copy (only) the black pixels and paste them in the same image b)我想(仅)复制黑色像素并将它们粘贴到同一图像中

c) When pasting, I want the paste to be offset by its "original" place by 20px (both x/y) c)粘贴时,我希望粘贴的“原始”位置偏移 20px(均为 x/y)

I try running the code below but get an error:我尝试运行下面的代码,但出现错误:

import cv2
test = Image.open('test.png')
np = Image.new('1', (1000, 300), 255)
mask = np.bitwise_and(test, np.roll(test, 20, (0,1)))
mask.save('mask.png')

I get AttributeError: 'Image' object has no attribute 'bitwise_and'我得到 AttributeError: 'Image' object has no attribute 'bitwise_and'

If image is logical (0/1) then:如果图像是逻辑的(0/1),那么:

res=np.bitwise_and(image, np.roll(image, 20, (0,1)))

You can do it like this:你可以这样做:

from PIL import Image
import numpy as np

# Load image and make Numpy array
im = Image.open('image.png').convert('L')
na = np.array(im)

# Get x,y coordinates of black pixels
Y, X = np.where(na==0)

# Make pixels 30 across and 30 down from them black
na[Y+30, X+30] = 0

# Convert back to PIL Image and save
Image.fromarray(na).save('result.png')

在此处输入图像描述

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM