簡體   English   中英

Python,Cv2,numpy表示圖片/圖像中的區域

[英]Python, Cv2, numpy to indicate areas in a picture/image

我想指定圖像中的某些區域。

要指定1個區域,我可以這樣做:

import cv2
import numpy as np

the_picture = cv2.imread("c:\\picture.jpg")

target_area = the_picture[300:360, 130:280]

target_area的類型是'numpy.ndarray'類型。

但是坐標列表是個問題。 我正在努力將坐標列表轉換為所需的值。

我想做的是:

the_picture = cv2.imread("c:\\picture.jpg")

list_of_areas = [
[300:360 , 130:280]
[300:360 , 440:540]
[400:460 , 0:130]
[400:460 , 250:400]
[400:460 , 560:740]

For area in list_of_areas:
    the_picture(area)     ### failed

這是坐標:

        x   y       x1  y1

Area1   130 300     280 360
Area2   440 300     540 360
Area3   0   400     130 460
Area4   250 400     400 460
Area5   560 400     740 460

我試圖給出一個如下所示的列表,但它不起作用。 我也嘗試在列表中制作字符串,將Square Brackets更改為Round Brackets既不起作用。

SyntaxError: invalid syntax

給出坐標的正確方法是什么?

如果我理解你想要做什么,請糾正我,如果我錯了,你可以通過保存和檢索區域坐標作為單個值來解決問題,而不是作為對

the_picture = cv2.imread("c:\\picture.jpg")

list_of_areas = [
[300, 360, 130, 280],
[300, 360, 440, 540],
[400, 460, 0, 130],
[400, 460 , 250, 400],
[400, 460, 560, 740]]

For y,y1,x,x1 in list_of_areas:
    the_picture[y:y1, x:x1]

這就是你想要的。 (添加逗號並關閉括號)

list_of_areas = [np.index_exp[300:360 , 130:280],
np.index_exp[300:360 , 440:540],
np.index_exp[400:460 , 0:130],
np.index_exp[400:460 , 250:400],
np.index_exp[400:460 , 560:740]]

這將為您提供切片對象元組的列表

list_of_areas

[(slice(300, 360, None), slice(130, 280, None)),
 (slice(300, 360, None), slice(440, 540, None)),
 (slice(400, 460, None), slice(0, 130, None)),
 (slice(400, 460, None), slice(250, 400, None)),
 (slice(400, 460, None), slice(560, 740, None))]

現在來獲取你的子陣列

test = np.random.randint(0,255,(480,960,3)) # random RGB
out = [test[area] for area in list_of_areas]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM