简体   繁体   中英

Python: OpenCV - Selecting Region of an Image

I want to select the region where the Data Matrix is placed.

import cv2
from matplotlib import pyplot as plt

img1 = cv2.imread('C:\\Users\\MyAccount\\Desktop\\datamatrix.png')
dmc = img1[300:588, 1225:1512]
plt.imshow(dmc)
plt.show()

I only receive a slim white area, but not a single region of this matrix. The ROI-Formular is [y:y+h, x:x+w], but it is not working.

The image has the size 1240 x 626.

The matrix has the attributes: left=938, top=323, width=287, height=288.

在此处输入图片说明

The coordinates you specify in your code don't correspond to what you describe.

Change them to:

dmc = img1[323:611, 938:1225]

You are correct about the ROI-Formular which is [y:y+h, x:x+w] , however the initial point on y coordinate is wrong that is why you are cropping the white region of the image.

You are probably looking for:

dmc = im[13:13+287, 938:938+287]
cv2.imshow('dmc', dmc)

Result:

在此处输入图片说明

If you like to have a relative formula:

import cv2

left=938
top=323
width=287
height=288

img = cv2.imread('temp.png', 0)
imgh, imgw = img.shape[:2]
# compute starting position of top
img = img[(imgh/2-height)/2:(imgh/2-height)/2+height, left:left+width]
cv2.imshow("result", img)
cv2.waitKey()

结果图像

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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