{"id":7856,"date":"2023-10-06T14:28:39","date_gmt":"2023-10-06T22:28:39","guid":{"rendered":"https:\/\/live-cometml.pantheonsite.io\/?p=7856"},"modified":"2025-04-24T17:05:51","modified_gmt":"2025-04-24T17:05:51","slug":"pneumonia-diagnosis-detection-with-opencv","status":"publish","type":"post","link":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/","title":{"rendered":"Pneumonia Diagnosis Detection with OpenCV"},"content":{"rendered":"\n<link rel=\"canonical\" href=\"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\">\n\n\n\n<div class=\"fi fj fk fl fm\">\n<div class=\"ab ca\">\n<div class=\"ch bg eu ev ew ex\">\n<figure class=\"lw lx ly lz ma mb lt lu paragraph-image\">\n<div class=\"mc md ec me bg mf\" tabindex=\"0\" role=\"button\">\n<figure><img loading=\"lazy\" decoding=\"async\" class=\"bg mg mh c\" role=\"presentation\" src=\"https:\/\/miro.medium.com\/v2\/resize:fit:700\/1*YJg_0hfDZoooJRFLZczhcw.jpeg\" alt=\"\" width=\"700\" height=\"467\"><\/figure><div class=\"lt lu lv\"><picture><\/picture><\/div>\n<\/div><figcaption class=\"mi mj mk lt lu ml mm be b bf z dw\" data-selectable-paragraph=\"\">Photo by <a class=\"af mn\" href=\"https:\/\/unsplash.com\/@nci?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" target=\"_blank\" rel=\"noopener ugc nofollow\">National Cancer Institute<\/a> on <a class=\"af mn\" href=\"https:\/\/unsplash.com\/photos\/tFkXIxtYVjw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText\" target=\"_blank\" rel=\"noopener ugc nofollow\">Unsplash<\/a><\/figcaption><\/figure>\n<p id=\"8454\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Pneumonia is a severe respiratory illness brought on by an infection that, particularly in groups at risk, can have life-threatening complications. It is essential to diagnose and treat pneumonia as soon as possible to maximize the patient\u2019s chances of recovery. The process of diagnosis is not easy and requires some medical laboratory tools and advanced medical skill, but we can use deep learning and computer vision to build a fast and easy tool that will help doctors be able to detect pneumonia.<\/p>\n<p id=\"c263\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Applications for image and video analysis, such as x-ray results, can be created using the open-source computer vision and machine learning software library known as <a class=\"af mn\" href=\"https:\/\/opencv.org\/\" target=\"_blank\" rel=\"noopener ugc nofollow\">OpenCV<\/a> (Open Source Computer Vision). Open CV is an open-source library for carrying out computer vision, machine learning, and image processing. We will discover how to use OpenCV to identify pneumonia in chest X-ray images in this lesson.<\/p>\n<h2 id=\"cffc\" class=\"nl nm fp be nn no np nq nr ns nt nu nv my nw nx ny nc nz oa ob ng oc od oe of bj\" data-selectable-paragraph=\"\"><strong class=\"al\">Install OpenCV<\/strong><\/h2>\n<p id=\"62c3\" class=\"pw-post-body-paragraph mo mp fp be b mq og ms mt mu oh mw mx my oi na nb nc oj ne nf ng ok ni nj nk fi bj\" data-selectable-paragraph=\"\">Installing OpenCV is the initial stage. There are various methods to install OpenCV depending on your operating system. Here are a few well-liked choices:<\/p>\n<p id=\"ff60\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Windows: On the main <a class=\"af mn\" href=\"https:\/\/opencv.org\/releases\/\" target=\"_blank\" rel=\"noopener ugc nofollow\">OpenCV website<\/a> use the pre-built binaries.<\/p>\n<p id=\"60b8\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Linux: OpenCV can be installed using the package manager included with your Linux distro. Run the following instruction in the terminal, for instance, on Ubuntu:<\/p>\n<pre class=\"ol om on oo op oq or os bo ot ba bj\"><span id=\"285a\" class=\"ou nm fp or b bf ov ow l ox oy\" data-selectable-paragraph=\"\">Install libopencv-dev with sudo apt-get<\/span><\/pre>\n<p id=\"61a9\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Mac OS: OpenCV can be set up using Homebrew the code below should be entered into the terminal.<\/p>\n<pre class=\"ol om on oo op oq or os bo ot ba bj\"><span id=\"40df\" class=\"ou nm fp or b bf ov ow l ox oy\" data-selectable-paragraph=\"\">Brew install opencv<\/span><\/pre>\n<p id=\"2a96\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Once OpenCV is loaded, you can use the following Python code to check that it is working properly.<\/p>\n<pre class=\"ol om on oo op oq or os bo ot ba bj\"><span id=\"2128\" class=\"ou nm fp or b bf ov ow l ox oy\" data-selectable-paragraph=\"\"><span class=\"hljs-keyword\">import<\/span> cv2\n<span class=\"hljs-built_in\">print<\/span>(cv2.__version__)<\/span><\/pre>\n<p id=\"6497\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">You should see the version number displayed in the terminal if OpenCV was properly installed.<\/p>\n<h2 id=\"e675\" class=\"nl nm fp be nn no np nq nr ns nt nu nv my nw nx ny nc nz oa ob ng oc od oe of bj\" data-selectable-paragraph=\"\"><strong class=\"al\">Download the Dataset<\/strong><\/h2>\n<p id=\"f39a\" class=\"pw-post-body-paragraph mo mp fp be b mq og ms mt mu oh mw mx my oi na nb nc oj ne nf ng ok ni nj nk fi bj\" data-selectable-paragraph=\"\">The dataset that will be used to train our pneumonia detection algorithm can be downloaded next. We\u2019ll make use of the Chest X-Ray pictures (Pneumonia) <a class=\"af mn\" href=\"https:\/\/www.kaggle.com\/paultimothymooney\/chest-xray-pneumonia\" target=\"_blank\" rel=\"noopener ugc nofollow\">dataset <\/a>from Kaggle in this exercise. There are 5,856 chest X-ray images overall in the dataset, divided into two categories: pneumonia and normal.<\/p>\n<p id=\"d4c1\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">You must sign up for a Kaggle account and agree to the dataset\u2019s terms and conditions in order to obtain the dataset. Once you\u2019ve done that, type the following command in the terminal to obtain the dataset:<\/p>\n<pre class=\"ol om on oo op oq or os bo ot ba bj\"><span id=\"2914\" class=\"ou nm fp or b bf ov ow l ox oy\" data-selectable-paragraph=\"\">kaggle datasets download -d paultimothymooney\/chest-xray-pneumonia<\/span><\/pre>\n<p id=\"d883\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">A ZIP file containing the information will be downloaded. Create a subfolder on your local computer and extract the ZIP file.<\/p>\n<h2 id=\"ffaf\" class=\"nl nm fp be nn no np nq nr ns nt nu nv my nw nx ny nc nz oa ob ng oc od oe of bj\" data-selectable-paragraph=\"\">Prepare the Data<\/h2>\n<p id=\"ae3d\" class=\"pw-post-body-paragraph mo mp fp be b mq og ms mt mu oh mw mx my oi na nb nc oj ne nf ng ok ni nj nk fi bj\" data-selectable-paragraph=\"\">The data must then be prepared for our pneumonia recognition model\u2019s training. To create more training samples from the current ones, we\u2019ll employ a method called data augmentation. This is done to increase the performance of the model and help the model build faster. In order to create different versions of the same picture, data augmentation involves applying random transformations to the images, such as rotation, scaling, and flipping.<\/p>\n<p id=\"7472\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">We will make two directories to prepare the data: one for training pictures and one for validation images. 80% of the pictures will be used for training, and 20% will be used for validation.<\/p>\n<p id=\"2b64\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Here is the code to get the info ready:<\/p>\n<pre class=\"ol om on oo op oq or os bo ot ba bj\"><span id=\"2bf1\" class=\"ou nm fp or b bf ov ow l ox oy\" data-selectable-paragraph=\"\"><span class=\"hljs-keyword\">import<\/span> os\n<span class=\"hljs-keyword\">import<\/span> shutil\n<span class=\"hljs-keyword\">import<\/span> random\n\n<span class=\"hljs-comment\"># Define the paths<\/span>\ninput_dir = <span class=\"hljs-string\">'path\/to\/input\/dir'<\/span>\ntrain_dir = <span class=\"hljs-string\">'path\/to\/train\/dir'<\/span>\nval_dir = <span class=\"hljs-string\">'path\/to\/val\/dir'<\/span>\n\n<span class=\"hljs-comment\"># Create the directories<\/span>\nos.makedirs(train_dir, exist_ok=<span class=\"hljs-literal\">True<\/span>)\nos.makedirs(val_dir, exist_ok=<span class=\"hljs-literal\">True<\/span>)\n\n<span class=\"hljs-comment\"># Get the list of images<\/span>\nimage_paths = []\n<span class=\"hljs-keyword\">for<\/span> root, dirs, files <span class=\"hljs-keyword\">in<\/span> os.walk(input_dir):\n    <span class=\"hljs-keyword\">for<\/span> file <span class=\"hljs-keyword\">in<\/span> files:\n        <span class=\"hljs-keyword\">if<\/span> file.endswith(<span class=\"hljs-string\">'.jpeg'<\/span>):\n            image_paths.append(os.path.join(root, file))\n\n<span class=\"hljs-comment\"># Shuffle the images<\/span>\nrandom.shuffle(image_paths)\n\n<span class=\"hljs-comment\"># Split<\/span>\n\nsplit_idx = <span class=\"hljs-built_in\">int<\/span>(<span class=\"hljs-number\">0.8<\/span> * <span class=\"hljs-built_in\">len<\/span>(image_paths))\ntrain_image_paths = image_paths[:split_idx]\nval_image_paths = image_paths[split_idx:]<\/span><\/pre>\n<p id=\"6f8e\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Now copy the images to the directories. Change \u201cpath\/to\/input\/dir\u201d to the path to the directory where you extracted the information in this code. The paths to the directories where you want to keep the training and validation images, respectively, should be substituted for \u201cpath\/to\/train\/dir\u201d and \u201cpath\/to\/val\/dir.\u201d<\/p>\n<\/div>\n<\/div>\n<\/div>\n\n\n\n<div class=\"fi fj fk fl fm\">\n<div class=\"ab ca\">\n<div class=\"ch bg eu ev ew ex\">\n<blockquote class=\"ph\"><p id=\"d10f\" class=\"pi pj fp be pk pl pm pn po pp pq nk dw\" data-selectable-paragraph=\"\">Struggling to track and reproduce complex experiment parameters? Artifacts are just one of the many tools in the Comet toolbox to help ease model management. <a class=\"af mn\" href=\"https:\/\/www.comet.com\/site\/blog\/debugging-your-machine-learning-models-with-comet-artifacts\/?utm_source=heartbeat&amp;utm_medium=referral&amp;utm_campaign=AMS_US_EN_AWA_heartbeat_CTA\" target=\"_blank\" rel=\"noopener ugc nofollow\">Read our PetCam scenario to learn more.<\/a><\/p><\/blockquote>\n<\/div>\n<\/div>\n<\/div>\n\n\n\n<div class=\"fi fj fk fl fm\">\n<div class=\"ab ca\">\n<div class=\"ch bg eu ev ew ex\">\n<h2 id=\"665c\" class=\"nl nm fp be nn no np nq nr ns nt nu nv my nw nx ny nc nz oa ob ng oc od oe of bj\" data-selectable-paragraph=\"\"><strong class=\"al\">Train the model<\/strong><\/h2>\n<p id=\"b778\" class=\"pw-post-body-paragraph mo mp fp be b mq og ms mt mu oh mw mx my oi na nb nc oj ne nf ng ok ni nj nk fi bj\" data-selectable-paragraph=\"\">Using the training images we created in the previous stage, we must now train the pneumonia detection model. The core of our model will be a pre-trained convolutional neural network (CNN) named <a class=\"af mn\" href=\"https:\/\/keras.io\/api\/applications\/vgg\/\" target=\"_blank\" rel=\"noopener ugc nofollow\">VGG16<\/a>. The popular CNN architecture VGG16 has attained state-of-the-art success on numerous image recognition tasks after being trained on a sizable dataset of images.<\/p>\n<p id=\"85d3\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Here\u2019s the code to train the model:<\/p>\n<pre class=\"ol om on oo op oq or os bo ot ba bj\"><span id=\"3795\" class=\"ou nm fp or b bf ov ow l ox oy\" data-selectable-paragraph=\"\"><span class=\"hljs-keyword\">from<\/span> tensorflow.keras.models <span class=\"hljs-keyword\">import<\/span> Model\n<span class=\"hljs-keyword\">from<\/span> tensorflow.keras.layers <span class=\"hljs-keyword\">import<\/span> Dense, GlobalAveragePooling2D\n<span class=\"hljs-keyword\">from<\/span> tensorflow.keras.applications <span class=\"hljs-keyword\">import<\/span> VGG16\n<span class=\"hljs-keyword\">from<\/span> tensorflow.keras.preprocessing.image <span class=\"hljs-keyword\">import<\/span> ImageDataGenerator\n\n<span class=\"hljs-comment\"># Define the input shape of the images<\/span>\ninput_shape = (<span class=\"hljs-number\">224<\/span>, <span class=\"hljs-number\">224<\/span>, <span class=\"hljs-number\">3<\/span>)\n\n<span class=\"hljs-comment\"># Load the VGG16 model<\/span>\nbase_model = VGG16(weights=<span class=\"hljs-string\">'imagenet'<\/span>, include_top=<span class=\"hljs-literal\">False<\/span>, input_shape=input_shape)\n\n<span class=\"hljs-comment\"># Add a global average pooling layer<\/span>\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\n\n<span class=\"hljs-comment\"># Add a fully connected layer<\/span>\nx = Dense(<span class=\"hljs-number\">128<\/span>, activation=<span class=\"hljs-string\">'relu'<\/span>)(x)\n\n<span class=\"hljs-comment\"># Add the output layer<\/span>\noutput = Dense(<span class=\"hljs-number\">1<\/span>, activation=<span class=\"hljs-string\">'sigmoid'<\/span>)(x)\n\n<span class=\"hljs-comment\"># Define the model<\/span>\nmodel = Model(inputs=base_model.<span class=\"hljs-built_in\">input<\/span>, outputs=output)\n\n<span class=\"hljs-comment\"># Freeze the layers of the VGG16 model<\/span>\n<span class=\"hljs-keyword\">for<\/span> layer <span class=\"hljs-keyword\">in<\/span> base_model.layers:\n    layer.trainable = <span class=\"hljs-literal\">False<\/span>\n\n<span class=\"hljs-comment\"># Compile the model<\/span>\nmodel.<span class=\"hljs-built_in\">compile<\/span>(optimizer=<span class=\"hljs-string\">'adam'<\/span>, loss=<span class=\"hljs-string\">'binary_crossentropy'<\/span>, metrics=[<span class=\"hljs-string\">'accuracy'<\/span>])\n\n<span class=\"hljs-comment\"># Define the data generators for training and validation<\/span>\ntrain_datagen = ImageDataGenerator(rescale=<span class=\"hljs-number\">1.<\/span>\/<span class=\"hljs-number\">255<\/span>,\n                                   rotation_range=<span class=\"hljs-number\">10<\/span>,\n                                   width_shift_range=<span class=\"hljs-number\">0.1<\/span>,\n                                   height_shift_range=<span class=\"hljs-number\">0.1<\/span>,\n                                   shear_range=<span class=\"hljs-number\">0.1<\/span>,\n                                   zoom_range=<span class=\"hljs-number\">0.1<\/span>,\n                                   horizontal_flip=<span class=\"hljs-literal\">True<\/span>,\n                                   fill_mode=<span class=\"hljs-string\">'nearest'<\/span>)\n\nval_datagen = ImageDataGenerator(rescale=<span class=\"hljs-number\">1.<\/span>\/<span class=\"hljs-number\">255<\/span>)\n\ntrain_generator = train_datagen.flow_from_directory(train_dir,\n                                                    target_size=input_shape[:<span class=\"hljs-number\">2<\/span>],\n                                                    batch_size=<span class=\"hljs-number\">32<\/span>,\n                                                    class_mode=<span class=\"hljs-string\">'binary'<\/span>)\n\nval_generator = val_datagen.flow_from_directory(val_dir,\n                                                target_size=input_shape[:<span class=\"hljs-number\">2<\/span>],\n                                                batch_size=<span class=\"hljs-number\">32<\/span>,\n                                                class_mode=<span class=\"hljs-string\">'binary'<\/span>)\n\n<span class=\"hljs-comment\"># Train the model<\/span>\nmodel.fit(train_generator,\n          steps_per_epoch=<span class=\"hljs-built_in\">len<\/span>(train_generator),\n          epochs=<span class=\"hljs-number\">10<\/span>,\n          validation_data=val_generator,\n          validation_steps=<span class=\"hljs-built_in\">len<\/span>(val_generator))\n\n<\/span><\/pre>\n<p id=\"e253\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">First, we loaded the pre-trained weights from the ImageNet dataset into the VGG16 model. We also include an output layer with a sigmoid activation function, a completely connected layer with 128 neurons, and a global average pooling layer. The VGG16 model\u2019s layers are frozen, and the Adam algorithm and binary cross-entropy loss are used to build the model. Following that, we specify data generators for training and validation that augment the data and rescale the pixel values to the [0, 1] range.<\/p>\n<p id=\"8293\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Using the fit approach and the training and validation data generators, we train the model for 10 epochs.<\/p>\n<h2 id=\"1fa1\" class=\"nl nm fp be nn no np nq nr ns nt nu nv my nw nx ny nc nz oa ob ng oc od oe of bj\" data-selectable-paragraph=\"\"><strong class=\"al\">Evaluate the model<\/strong><\/h2>\n<p id=\"2135\" class=\"pw-post-body-paragraph mo mp fp be b mq og ms mt mu oh mw mx my oi na nb nc oj ne nf ng ok ni nj nk fi bj\" data-selectable-paragraph=\"\">To determine how well the model generalizes to new data after training, we must evaluate its performance on a test set. To evaluate the model, we will make use of the dataset\u2019s test collection. Additionally, we will display some illustrations of both properly and incorrectly classified images.<\/p>\n<p id=\"be0e\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Use the code below to evaluate the model and display some instances.<\/p>\n<pre class=\"ol om on oo op oq or os bo ot ba bj\"><span id=\"16fb\" class=\"ou nm fp or b bf ov ow l ox oy\" data-selectable-paragraph=\"\"><span class=\"hljs-keyword\">import<\/span> numpy <span class=\"hljs-keyword\">as<\/span> np\n<span class=\"hljs-keyword\">import<\/span> matplotlib.pyplot <span class=\"hljs-keyword\">as<\/span> plt\n\n<span class=\"hljs-comment\"># Define the path to the test directory<\/span>\ntest_dir = <span class=\"hljs-string\">'path\/to\/input\/dir\/chest_xray\/test'<\/span>\n\n<span class=\"hljs-comment\"># Define the data generator for test<\/span>\ntest_datagen = ImageDataGenerator(rescale=<span class=\"hljs-number\">1.<\/span>\/<span class=\"hljs-number\">255<\/span>)\n\ntest_generator = test_datagen.flow_from_directory(test_dir,\n                                                  target_size=input_shape[:<span class=\"hljs-number\">2<\/span>],\n                                                  batch_size=<span class=\"hljs-number\">32<\/span>,\n                                                  class_mode=<span class=\"hljs-string\">'binary'<\/span>,\n                                                  shuffle=<span class=\"hljs-literal\">False<\/span>)\n\n<span class=\"hljs-comment\"># Evaluate the model on the test set<\/span>\nloss, accuracy = model.evaluate(test_generator, steps=<span class=\"hljs-built_in\">len<\/span>(test_generator))\n<span class=\"hljs-built_in\">print<\/span>(<span class=\"hljs-string\">f'Test accuracy: <span class=\"hljs-subst\">{accuracy:<span class=\"hljs-number\">.2<\/span>f}<\/span>'<\/span>)\n\n<span class=\"hljs-comment\"># Get the predictions and true labels<\/span>\npredictions = model.predict(test_generator, steps=<span class=\"hljs-built_in\">len<\/span>(test_generator))\npredictions = np.squeeze(predictions)\ntrue_labels = test_generator.labels\n\n<span class=\"hljs-comment\"># Get the image filenames<\/span>\nfilenames = test_generator.filenames\n\n<span class=\"hljs-comment\"># Find the indices of the correctly and incorrectly classified images<\/span>\ncorrect_indices = np.where((predictions &gt;= <span class=\"hljs-number\">0.5<\/span>) == true_labels)[<span class=\"hljs-number\">0<\/span>]\nincorrect_indices = np.where((predictions &gt;= <span class=\"hljs-number\">0.5<\/span>) != true_labels)[<span class=\"hljs-number\">0<\/span>]\n\n<span class=\"hljs-comment\"># Plot some correctly classified images<\/span>\nplt.figure(figsize=(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">10<\/span>))\n<span class=\"hljs-keyword\">for<\/span> i, idx <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-built_in\">enumerate<\/span>(correct_indices[:<span class=\"hljs-number\">9<\/span>]):\n    plt.subplot(<span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">3<\/span>, i+<span class=\"hljs-number\">1<\/span>)\n    img = plt.imread(os.path.join(test_dir, filenames[idx]))\n    plt.imshow(img, cmap=<span class=\"hljs-string\">'gray'<\/span>)\n    plt.title(<span class=\"hljs-string\">'PNEUMONIA'<\/span> <span class=\"hljs-keyword\">if<\/span> predictions[idx] &gt;= <span class=\"hljs-number\">0.5<\/span> <span class=\"hljs-keyword\">else<\/span> <span class=\"hljs-string\">'NORMAL'<\/span>)\n    plt.axis(<span class=\"hljs-string\">'off'<\/span>)\n\n<span class=\"hljs-comment\"># Plot some incorrectly classified images<\/span>\nplt.figure(figsize=(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">10<\/span>))\n<span class=\"hljs-keyword\">for<\/span> i, idx <span class=\"hljs-keyword\">in<\/span> <span class=\"hljs-built_in\">enumerate<\/span>(incorrect_indices[:<span class=\"hljs-number\">9<\/span>]):\n    plt.subplot(<span class=\"hljs-number\">3<\/span>, <span class=\"hljs-number\">3<\/span>, i+<span class=\"hljs-number\">1<\/span>)\n    img = plt.imread(os.path.join(test_dir, filenames[idx]))\n    plt.imshow(img, cmap=<span class=\"hljs-string\">'gray'<\/span>)\n    plt.title(<span class=\"hljs-string\">'PNEUMONIA'<\/span> <span class=\"hljs-keyword\">if<\/span> predictions[idx] &gt;= <span class=\"hljs-number\">0.5<\/span> <span class=\"hljs-keyword\">else<\/span> <span class=\"hljs-string\">'NORMAL'<\/span>)\n    plt.axis(<span class=\"hljs-string\">'off'<\/span>)\n\nplt.show()<\/span><\/pre>\n<p id=\"b42c\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">In this code, we created a test and evaluation set data generator to assess the model. We also get the predictions and true labels for the test set and find the indices of the correctly and incorrectly classified images. Then, using Matplotlib, we plot some instances of properly and incorrectly classified images.<\/p>\n<h2 id=\"3428\" class=\"nl nm fp be nn no np nq nr ns nt nu nv my nw nx ny nc nz oa ob ng oc od oe of bj\" data-selectable-paragraph=\"\"><strong class=\"al\">Conclusion<\/strong><\/h2>\n<p id=\"1420\" class=\"pw-post-body-paragraph mo mp fp be b mq og ms mt mu oh mw mx my oi na nb nc oj ne nf ng ok ni nj nk fi bj\" data-selectable-paragraph=\"\">In this tutorial, we built a pneumonia detection model using OpenCV and TensorFlow. We read, processed, and visualized the images using OpenCV, and we trained and tested the model using TensorFlow. The model was successful in classifying the majority of the test set\u2019s images with a high degree of precision.<\/p>\n<p id=\"e145\" class=\"pw-post-body-paragraph mo mp fp be b mq mr ms mt mu mv mw mx my mz na nb nc nd ne nf ng nh ni nj nk fi bj\" data-selectable-paragraph=\"\">Computer vision can be a huge asset to medical diagnostics. While they\u2019re not a replacement for trained healthcare providers, they can decrease time to diagnosis and improve diagnostic accuracy. You can see more CV medical use-cases in action <a class=\"af mn\" href=\"https:\/\/arxiv.org\/pdf\/2203.15269.pdf\" target=\"_blank\" rel=\"noopener ugc nofollow\">here.<\/a><\/p>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Photo by National Cancer Institute on Unsplash Pneumonia is a severe respiratory illness brought on by an infection that, particularly in groups at risk, can have life-threatening complications. It is essential to diagnose and treat pneumonia as soon as possible to maximize the patient\u2019s chances of recovery. The process of diagnosis is not easy and [&hellip;]<\/p>\n","protected":false},"author":100,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"customer_name":"","customer_description":"","customer_industry":"","customer_technologies":"","customer_logo":"","footnotes":""},"categories":[6,7],"tags":[],"coauthors":[198],"class_list":["post-7856","post","type-post","status-publish","format-standard","hentry","category-machine-learning","category-tutorials"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v25.9 (Yoast SEO v25.9) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Pneumonia Diagnosis Detection with OpenCV - Comet<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Pneumonia Diagnosis Detection with OpenCV\" \/>\n<meta property=\"og:description\" content=\"Photo by National Cancer Institute on Unsplash Pneumonia is a severe respiratory illness brought on by an infection that, particularly in groups at risk, can have life-threatening complications. It is essential to diagnose and treat pneumonia as soon as possible to maximize the patient\u2019s chances of recovery. The process of diagnosis is not easy and [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/\" \/>\n<meta property=\"og:site_name\" content=\"Comet\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/cometdotml\" \/>\n<meta property=\"article:published_time\" content=\"2023-10-06T22:28:39+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-04-24T17:05:51+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/miro.medium.com\/v2\/resize:fit:700\/1*YJg_0hfDZoooJRFLZczhcw.jpeg\" \/>\n<meta name=\"author\" content=\"Sandy M\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@Cometml\" \/>\n<meta name=\"twitter:site\" content=\"@Cometml\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Sandy M\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Pneumonia Diagnosis Detection with OpenCV - Comet","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/","og_locale":"en_US","og_type":"article","og_title":"Pneumonia Diagnosis Detection with OpenCV","og_description":"Photo by National Cancer Institute on Unsplash Pneumonia is a severe respiratory illness brought on by an infection that, particularly in groups at risk, can have life-threatening complications. It is essential to diagnose and treat pneumonia as soon as possible to maximize the patient\u2019s chances of recovery. The process of diagnosis is not easy and [&hellip;]","og_url":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/","og_site_name":"Comet","article_publisher":"https:\/\/www.facebook.com\/cometdotml","article_published_time":"2023-10-06T22:28:39+00:00","article_modified_time":"2025-04-24T17:05:51+00:00","og_image":[{"url":"https:\/\/miro.medium.com\/v2\/resize:fit:700\/1*YJg_0hfDZoooJRFLZczhcw.jpeg","type":"","width":"","height":""}],"author":"Sandy M","twitter_card":"summary_large_image","twitter_creator":"@Cometml","twitter_site":"@Cometml","twitter_misc":{"Written by":"Sandy M","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/#article","isPartOf":{"@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/"},"author":{"name":"Sandy M","@id":"https:\/\/www.comet.com\/site\/#\/schema\/person\/46eba004d124beb6d3592cf6728f43d6"},"headline":"Pneumonia Diagnosis Detection with OpenCV","datePublished":"2023-10-06T22:28:39+00:00","dateModified":"2025-04-24T17:05:51+00:00","mainEntityOfPage":{"@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/"},"wordCount":954,"publisher":{"@id":"https:\/\/www.comet.com\/site\/#organization"},"image":{"@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/#primaryimage"},"thumbnailUrl":"https:\/\/miro.medium.com\/v2\/resize:fit:700\/1*YJg_0hfDZoooJRFLZczhcw.jpeg","articleSection":["Machine Learning","Tutorials"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/","url":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/","name":"Pneumonia Diagnosis Detection with OpenCV - Comet","isPartOf":{"@id":"https:\/\/www.comet.com\/site\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/#primaryimage"},"image":{"@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/#primaryimage"},"thumbnailUrl":"https:\/\/miro.medium.com\/v2\/resize:fit:700\/1*YJg_0hfDZoooJRFLZczhcw.jpeg","datePublished":"2023-10-06T22:28:39+00:00","dateModified":"2025-04-24T17:05:51+00:00","breadcrumb":{"@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/#primaryimage","url":"https:\/\/miro.medium.com\/v2\/resize:fit:700\/1*YJg_0hfDZoooJRFLZczhcw.jpeg","contentUrl":"https:\/\/miro.medium.com\/v2\/resize:fit:700\/1*YJg_0hfDZoooJRFLZczhcw.jpeg"},{"@type":"BreadcrumbList","@id":"https:\/\/www.comet.com\/site\/blog\/pneumonia-diagnosis-detection-with-opencv\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.comet.com\/site\/"},{"@type":"ListItem","position":2,"name":"Pneumonia Diagnosis Detection with OpenCV"}]},{"@type":"WebSite","@id":"https:\/\/www.comet.com\/site\/#website","url":"https:\/\/www.comet.com\/site\/","name":"Comet","description":"Build Better Models Faster","publisher":{"@id":"https:\/\/www.comet.com\/site\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.comet.com\/site\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.comet.com\/site\/#organization","name":"Comet ML, Inc.","alternateName":"Comet","url":"https:\/\/www.comet.com\/site\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.comet.com\/site\/#\/schema\/logo\/image\/","url":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2025\/01\/logo_comet_square.png","contentUrl":"https:\/\/www.comet.com\/site\/wp-content\/uploads\/2025\/01\/logo_comet_square.png","width":310,"height":310,"caption":"Comet ML, Inc."},"image":{"@id":"https:\/\/www.comet.com\/site\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/cometdotml","https:\/\/x.com\/Cometml","https:\/\/www.youtube.com\/channel\/UCmN63HKvfXSCS-UwVwmK8Hw"]},{"@type":"Person","@id":"https:\/\/www.comet.com\/site\/#\/schema\/person\/46eba004d124beb6d3592cf6728f43d6","name":"Sandy M","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.comet.com\/site\/#\/schema\/person\/image\/73e571000fd489681999ca76cba0070b","url":"https:\/\/secure.gravatar.com\/avatar\/b91e4581668129edd364e880f0a56403a4ab1598cbb65e62ca9348c6db10ba72?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/b91e4581668129edd364e880f0a56403a4ab1598cbb65e62ca9348c6db10ba72?s=96&d=mm&r=g","caption":"Sandy M"},"url":"https:\/\/www.comet.com\/site\/blog\/author\/mondaysandy3gmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts\/7856","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/users\/100"}],"replies":[{"embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/comments?post=7856"}],"version-history":[{"count":1,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts\/7856\/revisions"}],"predecessor-version":[{"id":15511,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/posts\/7856\/revisions\/15511"}],"wp:attachment":[{"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/media?parent=7856"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/categories?post=7856"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/tags?post=7856"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.comet.com\/site\/wp-json\/wp\/v2\/coauthors?post=7856"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}