【问题标题】:Changing the color of each 10th and 11th pixel on image更改图像上每个第 10 和第 11 像素的颜色
【发布时间】:2022-01-01 10:35:01
【问题描述】:

我有一个与 cv2 相关的问题。我正在尝试将偶数行上的每个第 10 个像素和奇数行上的每个第 11 个像素的颜色更改为红色。我试图选择一个特定的行,但我不能。请帮忙

import cv2
import matplotlib.pyplot as plt
# read image
image = cv2.imread('2161382.jpg')
im_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# resize image
resized_img = cv2.resize(im_rgb,(500,500))
img_width = resized_img.shape[1]
img_height = resized_img.shape[0]

# Change individual pixel value (y,x)
resized_img[200, 10] = (255,0,0)
for row in resized_img:
    if row.all() % 2 == 0:
        resized_img[:,row + 11] = (255,0,0)
            

    
# On your own create a cycle where you can change the color of every N-th pixel on the odd row 
# and every M-th pixel on the even row to a different colour 
                      
%matplotlib notebook
plt.figure(figsize=(10,10))
plt.imshow(resized_img)

【问题讨论】:

  • 提示:您可以使用带有起始值和步长值的切片符号。
  • 您的row.all() 没有按照您的想法执行。你需要for y, row in enumerate(resized_img): / if y % 2 == 0: /

标签: python opencv matplotlib


【解决方案1】:

您需要检查行号。 row.all 不这样做。这有效:

# Change individual pixel value (y,x)
resized_img[200, 10] = (255,0,0)
for y,row in enumerate(resized_img):
    if y % 2:
        row[11] = (255,0,0)
    else:
        row[10] = (255,0,0)

【讨论】:

  • 不应该把条件倒过来,还是改成if y % 2:。赔率第 11 个像素,偶数第 10 个像素。
  • 嗯,是的,我认为原始代码至少部分正确。不是。
  • 谢谢!我试过你的代码,但它只能工作一次,而不是整个图像
【解决方案2】:

您根本不需要循环,您需要更快、更简单的索引。索引设置使用:

array[START:END:STEP]

如你所愿:

# Make image of 4 rows 22 columns of zeroes
im = np.zeros((4,22), np.uint8)

看起来像这样:

array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
      dtype=uint8)

现在使用索引更改一些值:

# Start at row 0 and on every 2nd row, set every 10th pixel to 7
im[0::2,::10] = 7

# Start at row 1 and on every 2nd row, set every 11th pixel to 9
im[1::2,::11] = 9

现在看起来像这样:

array([[7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0],
       [9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0],
       [9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
      dtype=uint8)

如果您有一个 3 通道 RGB 图像并且您想要设置 R、G 和 B,您可以添加第三个显式索引:

im[::2, ::10, :] = [255,0,0]

或者你可以省略它并保持隐含(感谢@Reti43):

im[::2, ::10] = [255,0,0]

【讨论】:

  • im[::2,::10] = [255, 0, 0] 对于 RGB 图像就足够了。也不清楚,但如果他想要每10个像素,从第10个开始,列索引需要更改为10::10
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多