使用 python 和 OpenCV 了解紅色區域之外的白色像素數量的最佳方法是什么?

我想從每個白色像素到高度 Y = 512 畫一條垂直直線可能是其中一種方法,但我不知道如何做到這一點
uj5u.com熱心網友回復:
我會這樣做,顯示沿途的所有步驟:
#!/usr/bin/env python3
import numpy as np
import cv2
# Load image
im = cv2.imread('R5qoS.png')
# Make a True/False mask of white pixels and save for debug
white = np.all(im==[255,255,255], axis=2)
cv2.imwrite('DEBUG-white.png', white*255)
# Make a True/False mask of red pixels and save for debug
red = np.all(im==[0,0,255], axis=2)
cv2.imwrite('DEBUG-red.png', red*255)
# Get all columns with red pixels in them
colsWithRed = np.argwhere(np.any(red==True, axis=0))
print(f'colsWithRed: {colsWithRed}')
# Get all columns with white pixels in them
colsWithWhite = np.argwhere(np.any(white==True, axis=0))
print(f'colsWithWhite: {colsWithWhite}')
# Get all columns with red and white
both = np.intersect1d(colsWithWhite,colsWithRed)
print(f'Columns with white and red: {both}')
除錯-white.png

除錯-red.png

輸出
Columns with white and red: [142 143 144 148 149 150 151 152 153 154 155 156 157 349 350 351 387 388 389 399 400 401]
注:axis=0意思是“往下看”。axis=1意思是“沿著行看”。axis=2意思是“查看 BGR/RGB 顏色通道”。
uj5u.com熱心網友回復:
如果我理解得很好,你想要的是,對于每個白色像素(即使是在相同 x 坐標中的那些),向下投射一條射線,并計算其中有多少與那些紅色湖的東西相交,對嗎?
如果是這樣,只有 numpy 就足夠了。想象一下對白色像素施加重力,使它們落到地上并計算每列的高度,乘以包含紅色像素的一維布爾陣列:
我的意思是,您可以在移除非白色像素后使用將影像從 2D 重塑為 1D,本質上成為給定列有多少白色像素的直方圖/陣列(Int 1D-Array) 。np.sum(a,axis=0)您可以將相同的方法應用于紅色像素,但不能計算它們,只是檢查一列是否有紅色像素(bool 1D-Array)。將這 2 個陣列相乘,您將得到另一個僅包含相交像素的陣列。
[編輯]:類似這樣的偽代碼:
import numpy as np
from PIL import Image
img_obj = Image.open('test.jpg') # assuming you're opening the image from a file, and using Pillow.
img_arr = np.array(img_obj) # This creates a 3D array (width, height, rgb. Like 512x512x3)
# This creates a 2D boolean array, 512x512x1. But watch it, some pixels might not be precisely 255.
white_pixels = img_arr[:,:,0] == 255 and img_arr[:,:,1] == 255 and img_arr[:,:,2] == 255
red_pixels = img_arr[:,:,0] == 255 and img_arr[:,:,1] == 0 and img_arr[:,:,2] == 0
white_columns = np.sum(white_pixels, axis=0) # This could be axis=1, not sure.
red_columns = np.sum(red_pixels, axis=0) > 0 # We just need booleans telling the presence of red in the column.
intersecting_columns = white_columns * red_columns
raycast_hits_count = np.sum(intersecting_columns)
可能會有一些轉換錯誤,例如將 int 轉換為布林值,或者像素值在 0 和 1 之間浮動,諸如此類。但核心概念是這個
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/529394.html
