python - 如何正确索引
问题描述
我试图查看图像数组中的各个像素值,看看它们是否高于某个阈值,如果它们满足这个条件,则找到它们的坐标。我无法正确索引 for 循环中的每个像素。有问题的图像是名为 mkv_array 的数据立方体的第一个切片,大小为 (1080,1920,500)。我在星域中寻找星星,因此必须满足的阈值基于图像中的背景水平和统计噪声(使用“sep”函数找到)。
cap = cv2.VideoCapture('/home/jryan/Videos/RMS/20211019_233512-50mm.mkv') #50mm
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = cap.get(cv2.CAP_PROP_FPS)
count = 500 #number of frames to iterate over
mkv_array = np.zeros((1080,1920,count)) #initialize array of zeros
for i in range(count):
frame = (cap.read()) # load frame from video, returns bool value and pixel array
a = frame[1] # want only pixel array, excludes bool value
gray_frame = cv2.cvtColor(np.float32(a), cv2.COLOR_BGR2GRAY) #convert from RGB to gray scale
mkv_array[:,:,i] += gray_frame #add frames to initial array
print(mkv_array.shape)
image_array = mkv_array[:,:,0].astype(np.float32) # first slice of a data cube
level = 5 #level above background noise
i = range(0,1080)
j = range(0,1920)
#find stars above certain threshold
for i in mkv_array[i,:,0]:
for j in mkv_array[:,j,0]:
bkg = sep.Background(image_array) # find background level of image array
print(bkg.globalback)
background = bkg.globalback #background level
print(bkg.globalrms)
noise = bkg.globalrms # noise in background
if mkv_array[i,j,0] < background + level*noise: # reject stars below threshold
continue
else:
labeled, num_objects = ndimage.label(mkv_array[i,j,0]) # label stars that meet condition
xy = np.array(ndimage.center_of_mass(image_array, labeled, range(1, num_objects+1))) #find coordinates for accepted stars
print(xy)
y,x = np.hsplit(xy,2)
我收到的错误在我的if mkv_array[i,j,0] < background + level*noise
声明行中:IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices.
我该如何解决这个问题?
解决方案
我如何解决这个问题:
xdim = 1080
ydim = 1920
#find stars above certain threshold
star_list_x = []
star_list_y = []
for j in range(xdim): #loop through all x coordinates
for k in range(ydim): #loop through all y coordinates
if mkv_array[j,k,0] < threshold: #skip if below threshold
continue
else: #keep if above threshold, append to star list.
star_list_x.append(j)
star_list_y.append(k)
star_list = np.array(list(zip(star_list_x, star_list_y)))