Nelly
Nelly

Reputation: 81

How can i read input only a part of the image without creating another image?

import cv2

fname = '1.png'
img=cv2.imread(fname, 0)
print (img)//the outcome is an array of values from 0 to 255 (grayscale)
ret, thresh = cv2.threshold(img, 254, 255, cv2.THRESH_BINARY)
thresh = cv2.bitwise_not(thresh)
nums, labels = cv2.connectedComponents(thresh, None, 4, cv2.CV_32S)
dst = cv2.convertScaleAbs(255.0*labels/nums)
cv2.imwrite(dest_dir+"output.png", dst)

that code works just fine, so i moved on to adjusting my code so it can take a portion of the image not the entire image:

from PIL import Image

    img = Image.open(fname)
    img2 = img.crop((int(xmin), int(yMin),int(xMax), int(yMax))

xmin ymin xmax ymax simply being the top left bottom right coordinates of the box. then i did img = cv2.imread(img2) to continue as the previous code but got an error, i printed img2 and got <PIL.Image.Image image mode=RGB size=54x10 at 0x7F4D283AFB70> how can i adjust it to be able to input that crop or image portion instead of fname in my code above, and kindly note i don't want to save img2 as an image and carry on from there because i need to work on the main image.

Upvotes: 0

Views: 1023

Answers (2)

Jeru Luke
Jeru Luke

Reputation: 21203

The simple answer is NO you cannot.

Open up your terminal /IDE and type in help(cv2.imread).

It clearly states that The function imread loads an image from the specified file and returns it. So in order to use cv2.imread() you must pass it in as a file not an image.

Your best bet would be to save your cropped image as a file and then read it.

Upvotes: 0

K P
K P

Reputation: 874

try cv2.imshow() instead of printing it. In order to see an image you cropped, you need to use cv2 function. here is a sample code:

import numpy as np
import cv2
# Load an color image in grayscale
img = cv2.imread('messi5.jpg',0)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 1

Related Questions