Search code examples
pythonopencvjupyter-notebooktexturesfeature-extraction

How to display test images at random from image test folder


I am using Haralick textures for a medical image classification problem. I want to iterate through a test folder with unlabeled images and print them in a jupyter notebook with prediction labels.

cv2.imshow() will output a random image to display, however, when I use plt.imshow() to display in a jupyter notebook the same image is returned.

# loop over the test images
test_path = 'data/test/test'
for file in glob.glob(test_path + "/*.jpeg"):
        # read the input image
        image = cv2.imread(file)

        # convert to grayscale
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # extract haralick texture from the image
        features = extract_features(gray)

# evaluate the model and predict label
prediction = clf_svm.predict(features.reshape(1, -1))[0]

# show the label
cv2.putText(image, prediction, (20,30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,255), 3)

# display the output image
#cv2.imshow("Test_Image", image)
#cv2.waitKey(0)

# display the output image in notebook
plt.imshow(image)
plt.show()

Using pyplot the same image is returned, I would like to return all (or a random subset) of images from the test folder.

If anything is not clear, I will clarify. Thank you.

example image


Solution

  • The core issue is your loop. You're not tabulating during your loop - you're using one single variable. The final item accessed by the loop will the the one that image, gray, and features are all based upon.

    The additional processing is then done outside of the loop on these single items, as is the output.

    You'll either want to bring all the processing inside your for loop, or you'll want to store your items in a list of some sort and then do further processing on the loop items, possibly with a pause to see different outputs.